[英]Nice way (for CPU) to wait for a free lock in Python
I have a generic class called "lockingValue" that may be referenced by several threads. 我有一个称为“ lockingValue”的通用类,可以被多个线程引用。 This is to prevent a race condition.
这是为了防止出现竞争状况。
class lockingValue(object):
def __init__(self,value=None):
self._locked=False
self._value=value
def _lock(self):
while self._locked:
pass
self._locked = True
def _unlock(self):
self._locked = False
def update(self,val):
self._lock()
self._value=val
def value(self):
return copy.copy(self._value)
What I'm looking for specifically is a nicer way to wait for the lock to become free. 我正在寻找的是一种等待锁释放的更好的方法。 The following is liable to peg the CPU and I would like to avoid it.
以下是容易挂住CPU的问题,我想避免使用它。
def _lock(self):
while self._locked:
pass
self._locked = True
Update: 更新:
I am interested in suggestions and examples of a better & safer design to do this sort of inner-process communication & tracking (tabulating progress across many threads for example). 我对更好和更安全的设计的建议和示例感兴趣,以进行这种内部流程通信和跟踪(例如,跨多个线程制表进度)。
Check out threading.Lock()
. 签出
threading.Lock()
。
import threading
class lockingValue(object):
def __init__(self,value=None):
self._lock = threading.Lock()
self._value = value
def _lock(self):
self._lock.acquire()
def _unlock(self):
self._lock.release()
def update(self, val):
self._lock()
self._value = val
self._unlock()
def value(self):
return copy.copy(self._value)
As your code stands right now, in your _lock
method, several threads could be waiting in the while loop, and multiple of them could make it out of the loop simultaneously if the OS thread scheduling conspired against you. 就像您的代码现在一样,在
_lock
方法中,while循环中可能有几个线程正在等待,如果操作系统线程调度不利于您,则其中的多个线程可能会同时使其退出循环。
Edit 编辑
Updated update
to unlock when finished based on khachik's comment. 根据卡其克的评论,更新
update
以在完成后解锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.