Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threads garbage collection

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?

like image 606
Falmarri Avatar asked Dec 20 '10 22:12

Falmarri


People also ask

Do threads get garbage collected?

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.

What happens to the thread when garbage collection?

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.

Does Python handle garbage collection?

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.

What triggers Python garbage collection?

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.


2 Answers

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!
like image 70
Robert Avatar answered Oct 10 '22 14:10

Robert


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

like image 25
Jochen Ritzel Avatar answered Oct 10 '22 14:10

Jochen Ritzel