-2

How do I close a python thread in order to make sure that it cleared from memory? Currently looking at using weakref but I do not know how to implement it for a class like what I have listed below. Threads are being closed (joined) but the memory seems to continuously increase. So I don't think they are being garbage collected.

threadlist = []
for r in something:
    t = MyThread()
    threadlist.append(t)

for thread in threadlist:
    thread.start()

for thread in threadlist:
    thread.join()
class MyThread(threading.Thread):
    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        # do something

  • The thread will terminate when the `run` method terminates. They won't be garbage collected till if `threadlist` still has a reference to them. – wwii Aug 10 '19 at 22:25
  • 1
    follow-up to previous comment, either do `del thread` in the `join` loop (after the join of course), or `del threadlist` after the loop – Tomerikoo Aug 10 '19 at 22:28
  • You need *both* `del thread` and `del threadlist` *after* the loop ends. Just deleting the reference in the loop doesn't help any. Clearing the list (or deleting it) will drop most of the references, but not the one to the last value in the list, since `thread` will remain active in the namespace. – Blckknght Aug 11 '19 at 00:33

1 Answers1

0

The threads will terminate when their run method terminates. They won't be garbage collected while threadlist holds a reference to them. .join blocks till the thread terminates so threadlist can be emptied after the for loop.

...
for thread in threadlist:
    thread.join()
threadlist = []
...

Don't remove threads from threadlist in the loop, you'll get unexpected results:
How to remove items from a list while iterating?
Python: Removing list element while iterating over list
and many more.

Or just let them run and remove them when they are done.

import threading, collections
class MyThread(threading.Thread):
    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        #print(self)
        time.sleep(random.randint(0, 10))

threadlist = collections.deque()

for r in range(5):
    t = MyThread()
    thread.start()
    threadlist.append(t)

while threadlist:
    if not threadlist[0].isAlive():
        threadlist.popleft()
    else:
        threadlist.rotate(-1)
wwii
  • 23,232
  • 7
  • 37
  • 77