我正在与测量设备交谈。我基本上发送命令并接收答案。但我提供了一种ask
发送命令并读回答案的方法。如果我锁定这个方法,我会因为调用的方法read
和write
锁定而陷入死锁。如果我不锁定另一个线程可能会在我阅读之前窃取答案或写入。你将如何实现这一点?
import threading
class Device(object):
lock = threading.Lock()
def ask(self, value):
# can't use lock here would block
self.write(value) # another thread could start reading the answer
return self.read()
def read(self):
with self.lock:
# read values from device
def write(self, value):
with self.lock:
# send command to device