Search This Blog

Showing posts with label synchronized. Show all posts
Showing posts with label synchronized. Show all posts

synchronized method in python

Java code


class AClass {
private int count =0;

public synchronized inc(){
count++;
}

public synchronized dec(){
count--;
}
}

Python code


import threading

class AClass(object):
def __init__(self):
self.__count = 0;
self.__lock = threading.RLock()

def inc(self):
with self.__lock:
self.__count += 1

def dec(self):
with self.__lock:
self.__count -= 1


see also

synchronized static method in python

Java code


class AClass {
private static int _count = 0;

public static synchronized inc(){
_count ++;
}

public static synchronized dec(){
_count --;
}
}

Python code


import threading

class AClass(object):
__count = 0
__lock = threading.RLock()

@classmethod
def inc(cls):
with cls.__lock:
cls.__count += 1

@classmethod
def dec(cls):
with cls.__lock:
cls.__count -= 1