Is a running thread eligable for garbage collection if the thread object is reasigned? For example:
class A(threading.Thread)
def run():
while True:
#Do stuff
a = A()
a.start()
time.sleep(60)
a = A()
at this point, even though thread A is still doing stuff, can the interpreter destroy the original A() thread? If it does, is there a way to prevent this from happening?
The Thread is not garbage collected because there are references to the threads that you cannot see. For example, there are references in the runtime system. When the Thread is created it is added to the current thread group.
7. What happens to the thread when garbage collection kicks off? Explanation: The thread is paused when garbage collection runs which slows the application performance. 8.
Python has an automated garbage collection. It has an algorithm to deallocate objects which are no longer needed. Python has two ways to delete the unused objects from the memory.
The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection. Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero.
My guess is no. There's still a reference to the thread in whatever structure Python uses to keep track of things. I'll test it out, but I'd be astonished if it didn't work.
EDIT Check it out:
#!/usr/bin/env python
import threading, time
class A(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name=name
self.count=0
def run(self):
while self.count<10:
print self.name, "Running!"
time.sleep(1)
self.count+=1
a=A("first")
a.start()
time.sleep(5)
a=A("second")
a.start()
first Running! first Running! first Running! first Running! first Running! second Running! first Running! second Running! first Running! first Running! second Running! first Running! second Running! first Running! second Running! second Running! second Running! second Running! second Running! second Running!
Threads wont get deleted like that, but I guess the problem you have is that threads disappear for no reason? A unhandled Exception will kill a thread without affecting the main thread! It only prints the traceback to stderr, but you might not see that ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With