Why print operation within signal handler may change deadlock situation?

蓝咒 提交于 2019-12-22 22:42:50

问题


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)

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?

(My python version is 2.6.5)


回答1:


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.



来源:https://stackoverflow.com/questions/10777610/why-print-operation-within-signal-handler-may-change-deadlock-situation

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