簡體   English   中英

父線程退出時,Python守護程序線程不會退出

[英]Python daemon thread does not exit when parent thread exits

我有一些Python代碼可以創建惡魔線程。 父線程幾乎立即結束,但守護程序線程保持打印睡眠。

import threading
import time
def int_sleep():
    for _ in range(1, 600):
        time.sleep(1)
        print("sleep")

def main():
    thread = threading.Thread(target=int_sleep)
    thread.daemon = True
    thread.start()
    time.sleep(2)
    print("main thread end...")

thread = threading.Thread(target=main)
thread.start()

內容sys.version:

'3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)]'

打印:

sleep

main thread end...

sleep

sleep

sleep

當父線程退出時,為什么Python守護程序線程不會退出?

如果為python線程指定thread.daemon = True ,那么只剩下守護進程時程序將立即停止。 發送到stdout的命令丟失了。

將其添加到名為main.py的文件中

import threading
import time

def int_sleep():
  for _ in range(1, 600):
    time.sleep(1)
    print("sleep")

def main():
  thread = threading.Thread(target=int_sleep)
  thread.daemon = True
  thread.start()
  time.sleep(2)
  print("main thread end...")

thread = threading.Thread(target=main)
thread.daemon = True
thread.start()

像這樣運行:

el@apollo:~/code/python/run01$ python --version
Python 2.7.6
el@apollo:~$ python main.py 
el@apollo:~$

看到它打印沒有,因為線程開始。 您將其設置為守護程序並啟動它。 然后程序結束了。

額外注意事項:如果將此代碼粘貼到python解釋器中,則所有打印語句都將顯示在終端上,因為守護程序永遠不會失去與stdout的連接。

閱讀更多: http//docs.python.org/2/library/threading.html

為了完整性,請查看本文。 https://joeshaw.org/2009/02/24/605/

監視是在守護程序線程內完成的。 Python文檔只說:

 A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. 

聽起來不錯,對吧? 這個線程偶爾會抓取一些數據,當程序關閉時我們不需要做任何特殊的事情。 是的,我記得以前我曾經相信的事情。

盡管全局解釋器鎖定阻止了Python無論如何都是真正的並發,但是在Python運行時開始自己的拆除過程之后,守護程序線程仍然可以執行。 此過程的一個步驟似乎是將globals()內的值設置為None,這意味着任何模塊解析都會導致AttributeError嘗試取消引用NoneType。 其他變體導致拋出TypeError。

我不確定這是一個已修復的錯誤,還是一個仍然存在的錯誤或按照設計行為。 但是,如果你看到怪異,那就把它放在腦后。

所以另一種方法是在退出標志上循環子線程,當你完成時可以在主標志中設置。 然后在主要處等待子線程死亡然后清理。

如果從python shell完成,我只能重現OP描述的行為('sleep'的無限輸出)。 如果從文件運行它按預期工作(幾行“睡眠”和一行“主線程結束......”)

類似地,如果作為文件運行,第二個程序會立即退出,但是當從python shell運行時,它還會打印無休止的'sleep'語句。

我的結論是:因為即使在“main”完成之后,作為python shell的線程仍繼續運行,所以防止守護進程在從python shell運行時被終止。

這可能被視為一個錯誤(即Python的行為根據腳本的運行方式而有所不同)或是否是預期的? 我推薦更有經驗的Pythonistas ......

BTW - 用Python 3.2.3測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM