gpt4 book ai didi

python 锁方法注解

转载 作者:太空狗 更新时间:2023-10-29 17:30:31 26 4
gpt4 key购买 nike

是否有一个 python 锁注释对 python 方法具有与 java 方法的“synchronized”关键字相同的效果?

最佳答案

我可以假设 python 中不存在内置功能,但您可以通过了解它在 Java 中的工作方式来实现它 this链接:

Every Java object created, including every Class loaded, has an associated lock or monitor. Putting code inside a synchronized block makes the compiler append instructions to acquire the lock on the specified object before executing the code, and release it afterwards (either because the code finishes normally or abnormally). Between acquiring the lock and releasing it, a thread is said to "own" the lock. At the point of Thread A wanting to acquire the lock, if Thread B already owns the it, then Thread A must wait for Thread B to release it.

所以也许这样的事情可以工作:

java中的同步语句:

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 中的同步方法:

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 功能,所以我可能错过了一些东西(或者我可能错过了这里的所有要点 :)),希望这个答案可以帮助到别人。

p>

注意:我创建的锁是一个类变量,所以线程同步发生在类级别,如果我们想在实例级别(仅)进行同步,我认为 java 是如何做到的,上面的代码必须改变.

关于python 锁方法注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4625182/

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