Interruptible thread join in Python

前端 未结 5 1858
暗喜
暗喜 2020-12-07 22:49

Is there any way to wait for termination of a thread, but still intercept signals?

Consider the following C program:



        
5条回答
  •  执笔经年
    2020-12-07 23:39

    Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests.

    There are two spots in the docs that give the reason for this (and possibly more).

    The first:

    From http://docs.python.org/library/signal.html#module-signal:

    Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); 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.

    The second, from http://docs.python.org/library/thread.html#module-thread:

    Threads interact strangely with interrupts: the KeyboardInterrupt exception will be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.)

    EDIT: There was a decent discussion of the mechanics of this on the python bug tracker here: http://bugs.python.org/issue1167930. Of course, it ends with Guido saying: " That's unlikely to go away, so you'll just have to live with this. As you've discovered, specifying a timeout solves the issue (sort of)." YMMV :-)

提交回复
热议问题