![](/img/trans.png)
[英]What happens to thread started in the class instance when all references to the instance are destroyed (Python)?
[英]What happens when you lose all references to a Python thread?
長話短說......當所有對threading.Thread
對象的引用都丟失時會發生什么,比如在這個函數中:
def myfunc():
def thread_func():
while True:
do_useful_things()
thethread = threading.Thread(target = thread_func)
thethread.run()
return
它看起來像線程繼續前進,但它表現得很奇怪,我想知道是否有可能發生奇怪的事情,因為垃圾收集器不正確地刪除它或其他東西。
或者線程繼續正常,即使產生線程沒有主動跟蹤它們本身(我知道threading
本身有獲取活動線程的方法)?
我不是線程專家,但是從我所知道的,如果你在它上面調用thethread.run
,它會在當前線程(執行的主線程,從而阻止執行)中執行,然后死掉。 在這種情況下,它將在函數結束后收集垃圾,作為該函數內的局部變量。
相反,如果你使用thethread.start()
它會被發送到它自己執行的單獨線程。 在這種情況下, threading
模塊中的映射始終保持對它的引用:
_active = {} # maps thread id to Thread object
所以,在這種情況下,總是至少有一個對你創建的線程的引用。 最終在執行其工作后將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.