无法中断lock.acquire()而我可以中断time.sleep() [英] cannot interrupt lock.acquire() whereas I can interrupt time.sleep()

查看:124
本文介绍了无法中断lock.acquire()而我可以中断time.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows中,python 3.4

In windows, python 3.4

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

触发死锁,而CTRL + C无法停止死锁.您必须终止该过程.

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

另一方面:

import time
time.sleep(100000)

可以随时通过CTRL + C中断(我已经阅读过其他一些SO问题/答案,但是效果很好)

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

两者都依赖于OS系统调用,所以为什么它对锁不起作用而对sleep起作用?是因为time.sleep(1000000)(大致)等同于for i in range(10000000): time.sleep(0.1)并且可以被精细打断吗?

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()

该程序将被阻止,并且不能被CTRL + C中断.您必须终止该过程.

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

现在,我正在创建一个线程,该线程使用线程锁执行阻塞调用.当按下CTRL + C时,我中断程序并释放锁.

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)

这篇关于无法中断lock.acquire()而我可以中断time.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆