2014-02-18 150 views
6

我有一些創建惡魔線程的Python代碼。父線程幾乎立即結束,但守護線程繼續打印睡眠。當父線程退出時,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的守護線程退出父線程退出時?

+0

退房的thread.daemon設置.. http://stackoverflow.com/questions/4330111/python-thread -daemon-property –

回答

5

如果您爲您的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() 

運行這樣的:

[email protected]:~/code/python/run01$ python --version 
Python 2.7.6 
[email protected]:~$ python main.py 
[email protected]:~$ 

見它打印任何事情,因爲線程啓動。您將其設置爲守護進程並啓動它。然後程序結束。其他注意事項:如果將此代碼粘貼到python解釋器中,所有打印語句都將顯示在終端上,因爲守護程序從不會丟失與stdout的連接。

瞭解更多:http://docs.python.org/2/library/threading.html

+1

爲什麼我們必須將主線程設置爲守護進程?如果我實現這樣的腳本...如果有一個線程停留在執行時,將所有的線程(在我們的例子守護線程)2秒 – user3388884

+0

嘿,我試圖運行此腳本確切,一切是睡眠定時器終止後印... – user3388884

+0

這是因爲你把它粘貼到一個終端,而不是一個程序,我在上面解釋了這種現象。 –

3

出於完整性檢查出這篇文章。 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被拋出。

我不確定這是一個已修正的錯誤還是存在的錯誤或每個設計的行爲。但是,如果你看到奇怪,請將它保存在你的腦後。

因此,另一種方法是在退出標誌上的子線程中循環,當完成後您可以在主標誌中設置該標誌。然後等待主要的子線程死亡,然後清理。

0

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

同樣,如果作爲文件運行,第二個程序立即退出,但同時也從python shell運行時打印無休止的「睡眠」語句。

我的結論是:因爲這是蟒蛇外殼線程將繼續即使在「主」完成運行,防止後臺程序(一個或多個)從蟒蛇shell中運行時被終止。

難道這被認爲是一個錯誤(即Python的行爲取決於腳本的運行方式是不同的),或者是預期?我聽從有經驗的Pythonistas ...

BTW - 與Python 3.2.3測試

相關問題