Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python instance variables thread-safe?

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?

like image 317
Shane Avatar asked Nov 29 '11 11:11

Shane


People also ask

Are instance variables thread-safe?

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.

Is Python threading thread-safe?

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.

Do threads share instance variables?

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.

Is Python truly multithreaded?

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.


1 Answers

You can use Locks, RLocks, Semaphores, Conditions, Events and Queues.
And this article helped me a lot.
Check it out: Laurent Luce's Blog

like image 63
aayoubi Avatar answered Oct 02 '22 15:10

aayoubi