Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you lose all references to a Python thread?

Long story short... what happens when all references to a threading.Thread object are lost, such as in this function:

def myfunc():
    def thread_func():
        while True:
            do_useful_things()
    thethread = threading.Thread(target = thread_func)
    thethread.run()
    return

It kinda looks like the thread keeps going, but it is behaving oddly and I wondered if there might be odd things happening because the garbage collector improperly deleted it or something.

Or do threads continue normally even if the spawning thread isn't actively keeping track of them itself (I know threading itself has means of getting the active threads)?

like image 706
Schilcote Avatar asked Oct 17 '22 21:10

Schilcote


1 Answers

I'm not an expert on threading but, from what I am aware, if you call thethread.run on it, it executes in the current thread (the main thread of execution thereby blocking execution) and then dies. In this case it will get garbage collected after the function ends as a local variable inside that function.

Instead, if you use thethread.start() it gets sent to a separate thread of its own where it executes. In this case, there's a mapping in the threading module that always keeps a reference to it:

_active = {}    # maps thread id to Thread object

so, in that case, there's always at least one reference to the thread you've created. This eventually gets removed after it performs its work.

like image 141
Dimitris Fasarakis Hilliard Avatar answered Oct 20 '22 09:10

Dimitris Fasarakis Hilliard