Search code examples
pythonpython-3.xthread-safetypython-multithreading

Python Daemon Thread Memory Leak?


If I create a daemon thread in Python (3.6+) and that daemon thread is finished execution, are its resources automatically freed up, or is it a memory leak? I looked around couldn't really find the answer...I assume it is freed up but paranoid and hoping someone can clarify.

I made a basic example:

import threading
import time

class Processor():
    
    def get_data_in_thread(self, id):
        for i in range(3):
            time.sleep(1)
            print(f'{id} count: {i}')

        #at this point is this thread's resources automatically garbage collected? Or is this a memory leak?

    def get_data(self, id):
        t = threading.Thread(target=self.get_data_in_thread, args=(id,))
        t.daemon = True
        t.start()


my_processor = Processor()
my_processor.get_data(17)

time.sleep(30)

When the work inside the daemon thread is finished in get_data_in_thread does the memory allocated within that thread free up automatically or is there a specific command I can use to self terminate its own daemon thread? Like del() or similar?

Thanks!


Solution

  • When a thread is destroyed, just like any other object, if it's no longer referenced (refcount goes to 0), it gets collected immediately. So do all the resources the thread referenced to, in your case the internal function variables, as they aren't referenced anywhere else.