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.
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.