为什么信号处理程序中的打印操作可能会改变死锁情况? [英] Why print operation within signal handler may change deadlock situation?
问题描述
我得到了一个简单的程序,如下所示:
I got simple program as below:
import threading
import time
import signal
WITH_DEADLOCK = 0
lock = threading.Lock()
def interruptHandler(signo, frame):
print str(frame), 'received', signo
lock.acquire()
try:
time.sleep(3)
finally:
if WITH_DEADLOCK:
print str(frame), 'release'
lock.release()
signal.signal(signal.SIGINT, interruptHandler)
for x in xrange(60):
print time.strftime("%H:%M:%S"), 'main thread is working'
time.sleep(1)
因此,如果启动该程序,甚至在3秒内按两次Ctrl + C,也不会出现死锁。每次按Ctrl + C,都会显示正确的行。
如果您更改WITH_DEADLOCK = 1并按Ctrl + C两次(3秒内),程序将被挂起。
So, if you start that program and even Ctrl+C is pressed twice within 3 seconds, there is no deadlock. Each time you press Ctrl + C proper line is displayed. If you change WITH_DEADLOCK=1 and you would press Ctrl+C twice (withing 3 seconds) then program will be hung.
有人可以解释为什么打印吗
Does anybody may explain why print operation make such difference?
(我的python版本是2.6.5)
(My python version is 2.6.5)
推荐答案
说实话,我认为JF Sebastian的评论在这里是最合适的答案-您需要使信号处理程序可重入,但目前尚不可以重入,而且最令人惊讶的是,如果没有print语句,它仍然可以工作。
To be honest I think J.F. Sebastian's comment is the most appropriate answer here - you need to make your signal handler reentrant, which it currently isn't, and it is mostly just surprising that it works anyway without the print statement.
这篇关于为什么信号处理程序中的打印操作可能会改变死锁情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!