Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: lifetime of terminated thread

How long is a thread available after is has terminated?

Background:

I have a CustomThread which extends Threads. Within that CustomThread I store a result. Now I’m curious how long I can access this result after the run() method has finished.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class CustomThread(threading.Thread):

    def __init__(self):

        self.result = None # will be set later in run()
        super().__init__()

>Solution :

First of all, when a thread terminates, it stops executing and releases all of its resources. Once a thread has terminated, you will no longer be able to access its result, as the thread object itself will no longer be available.

But, In case you want to access the result of a thread after it has terminated, you will need to store the result in a separate object that is not tied to the thread :-(.

class CustomThread(threading.Thread):

    def __init__(self):

        self.result = None # will be set later in run()
        super().__init__()

    def run(self):
        # Do something and then assign the result
        self.result = 42


t = CustomThread()
t.start()
t.join()

result = t.result  # You need to do this
print(result)  # prints 42

In the example I provided, the t object will remain in memory as long as there are references to it. Once all references to the t object are removed, it will be eligible for garbage collection, and the memory it occupies will be released.

It’s worth noting that the t object itself is separate from the thread that it represents. The thread will terminate when its run method finishes executing, but the t object will remain in memory until it is no longer needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading