2015-09-18 59 views
1

我有這樣的Python程序:Python的線程 - 阻塞操作 - 終止執行

from threading import Thread 

def foo(): 
    while True: 
    blocking_function() #Actually waiting for a message on a socket 

def run(): 
    Thread(target=foo).start() 

run() 

這個程序不與KeyboardInterrupt終止,由於運行foo()一個線程在退出之前主線程有機會終止。我試圖保持主線程活着,只需在調用run()後運行while True循環,但也不會退出程序(blocking_function()只是阻止線程運行,我猜,等待消息)。也嘗試在主線程捕獲KeyboardInterrupt異常,並呼籲sys.exit(0) - 相同的結果(我真的希望它殺死運行foo()線程,但顯然事實並非如此)

現在,我可以簡單地超時blocking_function()執行但那不好玩。我可以在KeyboardInterrupt或類似的東西上解鎖嗎?

主要目標:與阻塞的線程上終止Ctrl+C

回答

1

也許一種變通方法的一點點程序,但是你可以使用thread代替threading。這不是真的建議,但如果它適合你和你的程序,爲什麼不。

你需要讓你的程序運行,否則線程退出之後run()

import thread, time 

def foo(): 
    while True: 
    blocking_function() #Actually waiting for a message on a socket 

def run(): 
    thread.start_new_thread(foo,()) 

run() 
while True: 
    #Keep the main thread alive 
    time.sleep(1) 
+0

它用Ctrl + C終止現在。但是爲什麼'thread'這樣做而不是'threading'? – Amir