ddzialak
ddzialak

Reputation: 1080

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)

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)

Upvotes: 4

Views: 1869

Answers (1)

lxop
lxop

Reputation: 8605

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.

Upvotes: 1

Related Questions