【发布时间】:2012-07-04 19:20:04
【问题描述】:
有没有办法在python类中使用像java方法同步这样的监控线程同步来确保线程安全并避免竞争条件?
我想要一个类似监视器的同步机制,它只允许在我的类或对象中调用一个方法
【问题讨论】:
有没有办法在python类中使用像java方法同步这样的监控线程同步来确保线程安全并避免竞争条件?
我想要一个类似监视器的同步机制,它只允许在我的类或对象中调用一个方法
【问题讨论】:
您可能想看看python threading interface。对于简单的互斥功能,您可以使用 Lock 对象。您可以使用with 语句轻松做到这一点,例如:
...
lock = Lock()
...
with (lock):
# This code will only be executed by one single thread at a time
# the lock is released when the thread exits the 'with' block
...
另请参阅here,了解 python 中不同线程同步机制的概述。
Java 的 synchronized 没有 python 语言构造(但我猜它可以使用装饰器构建)
【讨论】:
我为它构建了一个简单的原型,这里有一个指向 GitHub 存储库的链接以了解所有详细信息:https://github.com/m-a-rahal/monitor-sync-python
我使用继承而不是装饰器,但也许我稍后会包含该选项
'Monitor' 超类如下所示:
import threading
class Monitor(object):
def __init__(self, lock = threading.Lock()):
''' initializes the _lock, threading.Lock() is used by default '''
self._lock = lock
def Condition(self):
''' returns a condition bound to this monitor's lock'''
return threading.Condition(self._lock)
init_lock = __init__
现在您需要做的就是定义自己的监视器是从这个类继承:
class My_Monitor_Class(Monitor):
def __init__(self):
self.init_lock() # just don't forget this line, creates the monitor's _lock
cond1 = self.Condition()
cond2 = self.Condition()
# you can see i defined some 'Condition' objects as well, very simple syntax
# these conditions are bound to the lock of the monitor
你也可以通过你自己的锁来代替
class My_Monitor_Class(Monitor):
def __init__(self, lock):
self.init_lock(lock)
您还需要使用监视器的锁来保护所有“公共”方法,如下所示:
class My_Monitor_Class(Monitor):
def method(self):
with self._lock:
# your code here
如果您想使用“私有”方法(在监视器内部调用),您可以不使用_lock 保护它们(否则线程会卡住),或者使用@ 987654323@ 代替监视器
有时监视器由“入口”和“出口”协议组成
monitor.enter_protocol()
<critical section>
monitor.exit_protocol()
在这种情况下,您可以利用 python 很酷的with 语句:3
只需像这样定义 __enter__ 和 __exit__ 方法:
class monitor(Monitor):
def __enter__(self):
with self._lock:
# enter_protocol code here
def __exit__(self, type, value, traceback):
with self._lock:
# exit_protocol code here
现在您需要做的就是使用with statement 调用监视器:
with monitor:
<critical section>
【讨论】: