代码来自PyMOTW signal chapter。为什么警报信号在由alarm_thread发出信号时不会被主线程立即处理。作者的输出显示警报线程完成后处理警报信号(alarm_thread.join()
返回)。
import signal
import time
import threading
def signal_handler(num, stack):
print time.ctime(), 'Alarm in', threading.currentThread()
signal.signal(signal.SIGALRM, signal_handler)
def use_alarm():
print time.ctime(), 'Setting alarm in', threading.currentThread()
signal.alarm(1)
print time.ctime(), 'Sleeping in', threading.currentThread()
time.sleep(3)
print time.ctime(), 'Done with sleep'
# Start a thread that will not receive the signal
alarm_thread = threading.Thread(target=use_alarm, name='alarm_thread')
alarm_thread.start()
time.sleep(0.1)
# Wait for the thread to see the signal (not going to happen!)
print time.ctime(), 'Waiting for', alarm_thread
alarm_thread.join()
print time.ctime(), 'Exiting normally'
作者输出:
$ python signal_threads_alarm.py
Sun Aug 17 12:06:00 2008 Setting alarm in <Thread(alarm_thread, started)>
Sun Aug 17 12:06:00 2008 Sleeping in <Thread(alarm_thread, started)>
Sun Aug 17 12:06:00 2008 Waiting for <Thread(alarm_thread, started)>;
Sun Aug 17 12:06:03 2008 Done with sleep
Sun Aug 17 12:06:03 2008 Alarm in <_MainThread(MainThread, started)>
Sun Aug 17 12:06:03 2008 Exiting normally
在我看来,输出应该如下。报警信号应由主线程before
报警线程睡眠完成处理,alarm_thread.join()
返回。
$ python signal_threads_alarm.py
Sun Aug 17 12:06:00 2008 Setting alarm in <Thread(alarm_thread, started)>
Sun Aug 17 12:06:00 2008 Sleeping in <Thread(alarm_thread, started)>
Sun Aug 17 12:06:00 2008 Waiting for <Thread(alarm_thread, started)>;
Sun Aug 17 12:06:03 2008 Alarm in <_MainThread(MainThread, started)>
Sun Aug 17 12:06:03 2008 Done with sleep
Sun Aug 17 12:06:03 2008 Exiting normally