我正在用python寫一個簡單的客戶端 - 服務器程序。在客戶端程序中,我創建了兩個線程(使用Python的線程模塊),一個用於接收,一個用於發送。接收線程不斷接收來自服務器端的字符串;而發送線程不斷監聽用戶輸入(使用raw_input())並將其發送到服務器端。這兩個線程使用Queue(本地同步,LIKE!)進行通信。Python:如何在其他線程中中斷raw_input()
的基本邏輯是類似以下內容:
接收線程:
global queue = Queue.Queue(0)
def run(self):
while 1:
receive a string from the server side
if the string is QUIT signal:
sys.exit()
else:
put it into the global queue
發送線程:
def run(self):
while 1:
str = raw_input()
send str to the server side
fetch an element from the global queue
deal with the element
正如你所看到的,在接收線程,我有一個if條件來測試服務器是否向客戶端發送了「退出信號」。如果有,那麼我希望整個程序停止。
這裏的問題是,大部分時間,發送線程被「raw_input()」阻塞並等待用戶輸入。當它被阻塞時,從另一個線程(接收線程)調用「sys.exit()」將不會立即終止發送線程。發送線程必須等待用戶鍵入內容並點擊回車按鈕。
有沒有人能激勵我如何解決這個問題?我不介意使用「raw_input()」的替代方法。其實我甚至不介意改變整個結構。
------------- -------------編輯
我在Linux機器上運行此,我的Python版本是2.7 0.5
你在Windows或Linux? – 2014-09-22 18:59:59
我正在使用linux – seemuch 2014-09-22 19:04:32
應該得到一個「仁慈的簡短代碼」徽章。 – 2015-08-03 11:28:49