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