簡體   English   中英

Python:線程處理:守護進程不應將stdin / stdout返回到主線程嗎?

[英]Python: threading: shouldn't a daemonized process return stdin/stdout to the main thread?

我以為是簡單的線程設置:生成守護進程子線程,然后等待鍵盤輸入停止:

    MASTER = threading.Thread(target=QueueMonitor())
    MASTER.setDaemon(True)
    MASTER.start()

    while True:
        ZZ = raw_input("running...\ntype 'ZZ' to quit \n\n")
        if 'ZZ' in ZZ:
            print "1. cleaning up... (this can take some time)"
            KILLALL = 1
            sys.exit()

在等待鍵盤輸入殺死所有內容的同時,子線程每隔“ x”秒循環並打印輸出。 代碼從不返回到“ ZZ”輸入,但似乎停留在子線程上:

thread:  1
thread:  2
thread:  3
thread:  4
thread:  5
thread:  6
thread:  7
thread:  ...

我究竟做錯了什么?

您應該調用start()而不是run() 后者在當前線程而不是新線程的上下文中調用線程函數。 結果,您的代碼永遠不會進入while循環。

使用'target'參數創建Thread對象時,目標應該是可調用對象,它將在啟動后在新線程中運行。 您在構造函數中調用了QueueMonitor(),因此它在創建線程之前運行。 由於您的QueueMonitor可以永遠運行,因此python永遠無法創建Thread。

只需傳遞函數名稱即可:

MASTER = threading.Thread(target=QueueMonitor)

暫無
暫無

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

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