gpt4 book ai didi

python - 正确锁定方法调用

转载 作者:行者123 更新时间:2023-11-28 22:58:48 26 4
gpt4 key购买 nike

我正在与测量设备通话。我基本上发送命令并接收答案。但我提供了一个方法 ask 来发送命令并读回答案。如果我锁定此方法,则会由于调用的方法 readwrite 锁定而陷入死锁。如果我不锁定另一个线程可能会在我阅读之前窃取答案或写。您将如何实现?

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

最佳答案

使用threading.RLock()避免单个线程内的争用:

A reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread. Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.

关于python - 正确锁定方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13532349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com