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

标签 python python-3.x multithreading

我找到了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/

相关文章:

python - 不再是漂浮物

python - 安装 pip pyicu 时出错

python - 赋值运算符左侧/右侧的不同切片行为

c - 双重免费或损坏(fasttop)错误c

multithreading - 如果前一个滴答声仍在运行,则执行旧版 VB6 计时器滴答声堆栈或跳过

python - python中slice(x,y)函数的使用

Python web2py 打印到屏幕

python - 在 Python 3 中将字符串转换为 int 或 float?

python - 如何编写 Django 查询,其中 WHERE 条件的左侧是数学表达式?

.net - 事件基本消费者 : max number of threads