简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM