我试图理解 Python 中的锁并编写了以下示例代码。
import threading
import time
LOCK = threading.Lock()
class Printer(threading.Thread):
def __init__(self, *args, **kwargs):
super(Printer, self).__init__(*args, **kwargs)
self.daemon = True
self.i = 0
def run(self):
while True:
with LOCK:
print(self.i)
self.i += 1
time.sleep(1)
raw_input('press enter to start thread\n')
Printer().start()
raw_input('press enter to pause thread\n')
LOCK.acquire()
raw_input('press enter to resume thread\n')
LOCK.release()
raw_input('press enter to exit program\n')
print('bye!')
这按预期工作并产生如下输出:
press enter to start thread
0
press enter to pause thread
1
2
3
4
press enter to resume thread
press enter to exit program
5
6
7
8
bye!
问题
为什么在 with
block 中缩进 time.sleep(1)
会破坏程序?
与
def run(self):
while True:
with LOCK:
print(self.i)
self.i += 1
time.sleep(1)
打印机不能被中断!
最佳答案
将您的代码更改为此并查看发生了什么:
import threading
import time
LOCK = threading.Lock()
class Printer(threading.Thread):
def __init__(self, *args, **kwargs):
super(Printer, self).__init__(*args, **kwargs)
self.daemon = True
self.i = 0
def run(self):
while True:
with LOCK:
print(self.i)
self.i += 1
time.sleep(1)
raw_input('press enter to start thread\n')
Printer().start()
raw_input('press enter to pause thread\n')
print('acquiring...')
LOCK.acquire()
print('acquired')
raw_input('press enter to resume thread\n')
LOCK.release()
raw_input('press enter to exit program\n')
print('bye!')
当你的代码尝试运行LOCK.acquire()
时,我认为with LOCK
和LOCK.acquire()
之间开始了一场竞争,并且该线程大多数时候赢得了游戏并获取 LOCK 1 秒。但在第一种方法中,当 Printer() 等待 1 秒时,主线程毫无问题地获取 LOCK,因为它是空闲的。我希望你能明白。抱歉我的语言:))
关于python - time.sleep 与 threading.Lock 的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494751/