gc 未删除线程模块的引用 [英] threading module's reference not removed by gc

查看:70
本文介绍了gc 未删除线程模块的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 gc 不会删除从 Threading.thread() 创建的对象.

I found gc doesn't remove the objects created from 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() 都完成了.

I created 10000 (test_thread()) + 1 (trace_memory()) threads and all of test_thread() were finished.

但是 refs:, bytes: 表明线程仍然被某些东西引用.

But refs:, bytes: show that threads are still referenced by something.

如何让 gc 删除它们?

推荐答案

你需要在最后停止线程:

You need to stop the threads at the end:

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()

这篇关于gc 未删除线程模块的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆