0

In windows, python 3.4

import threading
l = threading.Lock()
l.acquire()
l.acquire()

triggers a deadlock, and CTRL+C cannot stop it. You have to kill the process.

On the other hand:

import time
time.sleep(100000)

can be interrupted anytime with CTRL+C (I've read otherwise on some other SO questions/answers but it works fine)

Both rely on OS system calls so why is it not working for locks and it is working for sleep ? Is it because time.sleep(1000000) is (roughly) equivalent to for i in range(10000000): time.sleep(0.1) and thus can be finely interrupted?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    For the main thread, `time.sleep` waits on a Windows event that gets set by the signal handler. Waiting on this event is inconsistently supported in CPython, event in the latest 3.6 beta. – Eryk Sun Sep 17 '16 at 10:41

1 Answers1

1

I have found a workaround, which requires a threading and that the main program cooperates with the thread.

Let's consider this program:

import threading

l = threading.Lock()
l.acquire()
l.acquire()

That program blocks and cannot be interrupted by a CTRL+C. You have to kill the process.

Now, I'm creating a thread which performs the blocking call using a thread lock. When CTRL+C is pressed, I interrupt the program and release the lock.

There's no way to kill the thread otherwise than cooperating with it, so you have to know that the thread is doing:

import threading
import time,sys

l = threading.Lock()

def run():
    global l
    l.acquire()
    l.acquire()

t = threading.Thread(target=run)
t.start()

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        print("quitting")
        l.release()
        break

that can be adapted to other critical resources (sockets)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219