threading module's reference not removed by gc

两盒软妹~` 提交于 2021-01-29 00:45:04

问题


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

and below is result of 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

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

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

How can I make gc to remove them?


回答1:


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


来源:https://stackoverflow.com/questions/63293668/threading-modules-reference-not-removed-by-gc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!