Is there any way to use monitor thread synchronization like java methods synchronization,in python class to ensure thread safety and avoid race condition?
I want a monitor like synchronization mechanism that allows only one method call in my class or object
Advertisement
Answer
You might want to have a look at python threading interface. For simple mutual exclusion functionality you might use a Lock
object. You can easily do this using the with
statement like:
... lock = Lock() ... with (lock): # This code will only be executed by one single thread at a time # the lock is released when the thread exits the 'with' block ...
See also here for an overview of different thread synchronization mechanisms in python.
There is no python language construct for Java’s synchronized
(but I guess it could be built using decorators)