0

我正在運行兩個python線程(import threading)。他們兩人在open()呼叫被阻止;實際上他們試圖打開命名管道來寫入命名管道,所以這是一種正常行爲,直到有人試圖從命名管道讀取爲止。在線程中傳播系統調用中斷

總之,它看起來像:

import threading 

def f(): 
    open('pipe2', 'r') 

if __name__ == '__main__': 
    t = threading.Thread(target=f) 
    t.start() 
    open('pipe1', 'r') 

當我鍵入一個^ C,在主線程的open()被中斷(引發IOError並且errno == 4)。

我的問題是:t線程仍然在等待,我想傳播中斷行爲,以便使它也提升IOError

+0

如果在子線程開始前設置守護=真會發生什麼? – 2012-04-11 08:59:55

+0

沒有更多。而且,我的問題的目的不是要殺死線程,我希望他在收到信號後做一些事情(清理)。 – deathiop 2012-04-12 10:05:46

回答

0

我發現這個在python文檔:
「 ...只有主線程可以設置一個新的信號處理程序,主線程將接收信號(這是由Python信號模塊執行的唯一,即使底層線程實現支持向單獨線程發送信號),這意味着信號不能用作線程間通信的手段,而應該使用鎖定 「
也許你還應該檢查這些文檔:
exceptions.KeyboardInterrupt

library/signal.html

另一個想法是使用select在線程中異步讀取管道。這部作品在Linux中,不知道有關Windows(它不是​​最乾淨的,也不是最好的實現):

#!/usr/bin/python 

    import threading 
    import os 
    import select 

    def f(): 
      f = os.fdopen(os.open('pipe2', os.O_RDONLY|os.O_NONBLOCK)) 
      finput = [ f ] 
      foutput = [] 
      # here the pipe is scanned and whatever gets in will be printed out 
      # ...as long as 'getout' is False 
      while finput and not getout: 
        fread, fwrite, fexcep = select.select(finput, foutput, finput) 
        for q in fread: 
          if q in finput: 
            s = q.read() 
            if len(s) > 0: 
              print s 

    if __name__ == '__main__': 
      getout = False 
      t = threading.Thread(target=f) 
      t.start() 
      try: 
        open('pipe1', 'r') 
      except: 
        getout = True