I’m talking to a measurement device. I basically send commands and receive answers. But I’m providing a method ask that sends a command and reads back the answer. If I lock this method I get a deadlock due to the called methods read and write locking aswell. If I don’t lock another thread could steal the answer or write before I’m reading. How would you implement this?
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
Use
threading.RLock()to avoid contention within a single thread: