gpt4 book ai didi

python - 线程模块的引用未被 gc 删除

转载 作者:行者123 更新时间:2023-12-03 13:23:24 26 4
gpt4 key购买 nike

我找到了gc不会删除从 Threading.thread() 创建的对象.

# print memory status every 5sec
def trace_memory():
while True:
time.sleep(5)
print(mem_top())

# just print and end
def test_thread():
print('thread')

threading.Thread(target=trace_memory).start()

curr_count = 0
max_count = 10000
while max_count > curr_count:
threading.Thread(target=test_thread).start()
curr_count += 1
以下是 mem_top() 的结果:
refs:
10001 <class 'list'> [<unlocked _thread.lock object at 0x00000204DD680030>, <unlocked _thread.lock object at 0x00000204DD

bytes:
90120 [<unlocked _thread.lock object at 0x00000204DD680030>, <unlocked _thread.lock object at 0x00000204DD
我创建了 10000 ( test_thread() ) + 1 ( trace_memory() ) 线程和全部 test_thread()完成了。
但是 refs:, bytes: 表明线程仍然被某些东西引用。
如何制作 gc删除它们?

最佳答案

您需要在最后停止线程:

import threading, time, mem_top, gc


def trace_memory():
while True:
time.sleep(5)
print(mem_top.mem_top())

# just print and end
def test_thread():
print('thread')


def main():
threading.Thread(target=trace_memory).start()

curr_count = 0
max_count = 1000
threads = []
while max_count > curr_count:
thread = threading.Thread(target=test_thread)
thread.start()
threads.append(thread)
curr_count += 1

for thread in threads:
thread.join()


main()

关于python - 线程模块的引用未被 gc 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63293668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com