threading.Condition.wait()没有捕获SIGTERM

时间:2014-07-03 10:22:45

标签: python multithreading conditional-statements wait

我有以下代码,执行时等待被SIGINTSIGTERMSIGQUIT中断。初始化对象时,它会创建threading.Condition()acquires()它!然后程序注册信号处理程序,当接收到上述信号时,notify()release()被调用。注册信号处理程序后,它会在条件变量上调用wait()并阻塞。

当我尝试使用Ctrl-C停止该程序时,它没有响应。 IOW,_signal_handler()方法没有被调用。

# start

from signal import signal, SIGINT, SIGTERM, SIGQUIT
from threading import Condition

class A:
    def __init__(self):
        self._termination_signal = Condition()
        self._termination_signal.acquire(blocking=0)

    def _signal_handler(self, signum, frame):
        print "Received terminate request - signal = {0}".format(signum)
        del frame
        self._termination_signal.notify()
        self._termination_signal.release()
        return

    def register_and_wait(self):
        signal(SIGINT, self._signal_handler)
        signal(SIGTERM, self._signal_handler)
        signal(SIGQUIT, self._signal_handler)
        print "Waiting to be interrupted!"
        self._termination_signal.wait()      # control blocks here!
        print "Notified!!"

def main():
    a = A()
    a.register_and_wait()

if __name__ == "__main__":
    main()

# end

我做错了什么?!

1 个答案:

答案 0 :(得分:1)

似乎它挂在信号处理程序中试图获取条件变量的锁定。我不知道为什么,但另一个选择就是等待信号。

from signal import pause, signal, SIGINT, SIGTERM, SIGQUIT

class A:
    def __init__(self):
        self._signum = 0

    def _signal_handler(self, signum, frame):
        print "Received terminate request - signal = {0}".format(signum)
        self._signum = signum
        return

    def wait_for_signal(self):
        signal(SIGINT, self._signal_handler)
        signal(SIGTERM, self._signal_handler)
        signal(SIGQUIT, self._signal_handler)
        print "Pause until signaled"
        while self._signum == 0:
            pause()

def main():
    a = A()
    a.wait_for_signal()

main()

检查self._signum的原因是另一个信号唤醒pause()。一个简单的例子就是SIGALRM