OK, check following codes first:
class DemoClass(): def __init__(self): #### I really want to know if self.Counter is thread-safe. self.Counter = 0 def Increase(self): self.Counter = self.Counter + 1 def Decrease(self): self.Counter = self.Counter - 1 def DoThis(self): while True: Do something if A happens: self.Increase() else: self.Decrease() time.sleep(randomSecs) def DoThat(self): while True: Do other things if B happens: self.Increase() else: self.Decrease() time.sleep(randomSecs) def ThreadSafeOrNot(self): InterestingThreadA = threading.Thread(target = self.DoThis, args = ()) InterestingThreadA.start() InterestingThreadB = threading.Thread(target = self.DoThat, args = ()) InterestingThreadB.start()
I'm facing same situation as above. I really want to know if it's thread-safe for self.Counter
, well if not, what options do I have? I can only think of threading.RLock()
to lock this resource, any better idea?
Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.
Python is not by its self thread safe. But there are moves to change this: NoGil, etc. Removing the GIL does not make functions thread-safe.
Tip: Unlike class and instance field variables, threads cannot share local variables and parameters. The reason: Local variables and parameters allocate on a thread's method-call stack. As a result, each thread receives its own copy of those variables.
Python is NOT a single-threaded language. Python processes typically use a single thread because of the GIL. Despite the GIL, libraries that perform computationally heavy tasks like numpy, scipy and pytorch utilise C-based implementations under the hood, allowing the use of multiple cores.
You can use Locks, RLocks, Semaphores, Conditions, Events and Queues.
And this article helped me a lot.
Check it out: Laurent Luce's Blog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With