[英]cannot interrupt lock.acquire() whereas I can interrupt time.sleep()
在 Windows 中,python 3.4
import threading
l = threading.Lock()
l.acquire()
l.acquire()
觸發死鎖,CTRL+C 無法阻止。 你必須終止進程。
另一方面:
import time
time.sleep(100000)
可以隨時使用 CTRL+C 中斷(我已經閱讀了其他一些 SO 問題/答案,但效果很好)
兩者都依賴於操作系統系統調用,那么為什么它不適用於鎖而它適用於sleep
呢? 是因為time.sleep(1000000)
(大致)相當於for i in range(10000000): time.sleep(0.1)
,因此可以很好地中斷?
我找到了一個解決方法,它需要一個線程並且主程序與線程合作。
讓我們考慮這個程序:
import threading
l = threading.Lock()
l.acquire()
l.acquire()
該程序會阻塞並且不能被 CTRL+C 中斷。 你必須終止進程。
現在,我正在創建一個使用線程鎖執行阻塞調用的線程。 當按下 CTRL+C 時,我會中斷程序並釋放鎖定。
除了與它合作之外,沒有辦法殺死該線程,因此您必須知道該線程正在做什么:
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
可以適應其他關鍵資源(套接字)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.