python锁方法注释

2024-05-13 18:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个python锁注释,它对python方法的影响与java方法的“synchronized”关键字相同?


Tags: 方法关键字javasynchronized
2条回答

我有时会用这样的装饰:

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方法,或者在__init__中手动分配self._lock

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

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特性的第一堂课,所以也许我错过了一些东西(或者我错过了这里的所有要点),希望这个答案能帮助一些人。

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

相关问题 更多 >