cannot interrupt lock.acquire() whereas I can interrupt time.sleep()

后端 未结 1 953
夕颜
夕颜 2021-01-16 11:44

In windows, python 3.4

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

triggers a deadlock, and CTRL+C cannot stop it. You ha

相关标签:
1条回答
  • 2021-01-16 11:58

    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)

    0 讨论(0)
提交回复
热议问题