1

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Rurien
  • 359
  • 1
  • 13

1 Answers1

2

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()
Anmol Singh Jaggi
  • 8,376
  • 4
  • 36
  • 77