Are Python instance variables thread-safe?

后端 未结 4 1547
北荒
北荒 2020-12-13 02:38

OK, check following codes first:

class DemoClass():

    def __init__(self):
        #### I really want to know if self.Counter is thread-safe. 
        self         


        
相关标签:
4条回答
  • 2020-12-13 02:52

    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.

    0 讨论(0)
  • 2020-12-13 03:02

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

    0 讨论(0)
  • 2020-12-13 03:04

    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

    0 讨论(0)
  • 2020-12-13 03:06

    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.

    0 讨论(0)
提交回复
热议问题