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:
JavaScript
x
8
1
2
lock = Lock()
3
4
with (lock):
5
# This code will only be executed by one single thread at a time
6
# the lock is released when the thread exits the 'with' block
7
8
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)