Propagate system call interruptions in threads

感情迁移 提交于 2020-01-06 20:05:47

问题


I'm running two python threads (import threading). Both of them are blocked on a open() call; in fact they try to open named pipes in order to write in them, so it's a normal behaviour to block until somebody try to read from the named pipe.

In short, it looks like:

import threading

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

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

When I type a ^C, the open() in the main thread is interrupted (raises IOError with errno == 4).

My problem is: the t threads still waits, and I'd like to propagate the interruption behaviour, in order to make it raise IOError too.


回答1:


I found this in python docs:
" ... only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead. "
Maybe you should also check these docs:
exceptions.KeyboardInterrupt

library/signal.html

One other idea is to use select to read the pipe asynchronously in the threads. This works in Linux, not sure about Windows (it's not the cleanest, nor the best implementation):

   #!/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


来源:https://stackoverflow.com/questions/10102340/propagate-system-call-interruptions-in-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!