是否有一个python锁注释与python方法的效果与java方法的“synchronized”关键字相同?
答案 0 :(得分:15)
我可以假设python中不存在内置功能,但您可以通过this链接了解它在Java中的工作方式来实现它:
创建的每个Java对象,包括 每个类加载,都有一个关联 锁定或监视。把代码放在一个 synchronized块使编译器 附加指令以获取 之前锁定指定的对象 执行代码,然后释放它 之后(因为代码 正常或异常完成)。 在获得锁和之间 释放它,一个线程据说 “拥有”锁。在线程点 想要获得锁,如果 线程B已经拥有它,然后 线程A必须等待线程B 释放它。
所以也许这样的事情可以发挥作用:
java中的synchronized语句:
public class Java {
static private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
}
成了:
import threading
class Java:
cout = 0
lock = threading.RLock()
def increment():
with Java.lock:
Java.cout += 1
和Java中的synchronized方法:
public class Java {
static private int count = 0;
public synchronized void increment() {
count ++;
}
}
成为:
import threading
def synchronized(method):
""" Work with instance method only !!! """
def new_method(self, *arg, **kws):
with self.lock:
return method(self, *arg, **kws)
return new_method
class Java:
count = 0
lock = threading.RLock()
@synchronized
def incremenet(self):
Java.count += 1
明确比隐含更好。
注意:我在Java方面的知识非常有限,这是我关于这个Java特性的第一次演讲,所以也许我想念一些东西(或者我可能会错过这里的所有观点:)),希望这个答案可以帮助别人。
注意:我创建的锁是一个类变量,因此线程同步发生在类级别,如果我们想在实例级别(仅)进行同步,我认为java是如何做的,上面的代码必须改变
答案 1 :(得分:1)
我有时会使用这样的装饰器:
def synchronized(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
try:
_ = self._lock
except AttributeError:
self._lock = threading.Lock()
with self._lock:
return f(self, *args, **kwargs)
return wrapper
此解决方案在第一次调用修饰方法时具有竞争条件。避免此问题的最简单方法是在没有其他线程首先运行时调用一个synchronized方法,或者在self._lock
中手动分配__init__