There is no synchronized keyword in python similar to the one used in Java to synchronize the method, so in Python you implement the synchronization method, and we usually use threading. Lock () to implement. To get the lock when entering the function, release the lock when the function is released, so the implementation code looks very bad. Others on the internet also gave several other ways of implementation, but it does not look Mike.
Today, when I was working on a project, I suddenly realized that it was possible to use annotations to annotate the method as a synchronization method by Functools.
You first require a lock object in your own class and initialize the lock object when the class is initialized, for example:
Class Myworker (object):
def __init__ (self):
Self.lock = Threading. Lock () ...
...
Then create a synchronized function that decorates the concrete method of the specific object, and puts the method between the fetch/release lock to run, as follows
def synchronized (func):
@functools. Wraps (func)
def wrapper (self, *args, **kwargs): With
Self.lock:
return func (Self, *args, **kwargs) return
Wrapper
Finally, the standard method for using @synchronized on methods that need to be synchronized is the synchronization method, such as:
@synchronized
def Test (self):
...
The following is a complete example for reference only:
Import Threading Import Functools import Time def synchronized (func): @functools. Wraps (func) def wrapper (self, * args, **kwargs): With Self.lock:return func (self, *args, **kwargs) return wrapper class Myworke R (Object): Def __init__ (self): Self.lock = Threading. Lock () self.idx = 0 @synchronized def test1 (self): for I in range (1, one): Self.idx =
SELF.IDX + 1 print "Test1:" + str (SELF.IDX) time.sleep (1) @synchronized def test2 (self):
For I in range (1, one): Self.idx = self.idx + 1 print "TEST2:" + str (SELF.IDX)
Time.sleep (1) @synchronized def test3 (self): for I in range (1, one): Self.idx = self.idx + 1 Print "TEST3:" + str (SELF.IDX) time.sleep (1) worker = Myworker () threading. Thread (Target=worker.test1). Start () threading. Thread (Target=worker.test2). Start () threading. Thread (TARGET=WORKER.TEST3). Start ()