Are Python instance variables thread-safe?
You can use Locks, RLocks, Semaphores, Conditions, Events and Queues.
And this article helped me a lot.
Check it out: Laurent Luce's Blog
Using the instance field self.Counter
is thread safe or "atomic". Reading it or assigning a single value - even when it needs 4 bytes in memory, you will never get a half-changed value. But the operation self.Counter = self.Counter + 1
is not because it reads the value and then writes it - another thread could change the value of the field after it has been read and before it is written back.
So you need to protect the whole operation with a lock.
Since method body is basically the whole operation, you can use a decorator to do this. See this answer for an example: https://stackoverflow.com/a/490090/34088
No, it is not thread safe - the two threads are essentially modifying the same variable simultaneously. And yes, the solution is one of the locking mechanisms in the threading
module.
BTW, self.Counter
is an instance variable, not a class variable.