Are Python Instance Variables Thread-safe?
Solution 1:
You can use Locks, RLocks, Semaphores, Conditions, Events and Queues. And this article helped me a lot. Check it out: Laurent Luce's Blog
Solution 2:
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
Solution 3:
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.
Solution 4:
self.Counter
is an instance variable, so each thread has a copy.
If you declare the variable outside of __init__()
, it will be a class variable.
All instances of the class will share that instance.
Solution 5:
The Atomos library provides atomic (thread-safe) wrappers for Python primitives and objects, including atomic counters. It uses single-writer/multiple-reader locks.
Post a Comment for "Are Python Instance Variables Thread-safe?"