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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.