Is the += operator thread-safe in Python?

后端 未结 8 1513
萌比男神i
萌比男神i 2020-11-27 13:45

I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.

c = 0

def increment():
          


        
相关标签:
8条回答
  • 2020-11-27 14:20

    Single opcodes are thread-safe because of the GIL but nothing else:

    import time
    class something(object):
        def __init__(self,c):
            self.c=c
        def inc(self):
            new = self.c+1 
            # if the thread is interrupted by another inc() call its result is wrong
            time.sleep(0.001) # sleep makes the os continue another thread
            self.c = new
    
    
    x = something(0)
    import threading
    
    for _ in range(10000):
        threading.Thread(target=x.inc).start()
    
    print x.c # ~900 here, instead of 10000
    

    Every resource shared by multiple threads must have a lock.

    0 讨论(0)
  • 2020-11-27 14:23

    It's easy to prove that your code is not thread safe. You can increase the likelyhood of seeing the race condition by using a sleep in the critical parts (this simply simulates a slow CPU). However if you run the code for long enough you should see the race condition eventually regardless.

    from time import sleep
    c = 0
    
    def increment():
      global c
      c_ = c
      sleep(0.1)
      c = c_ + 1
    
    def decrement():
      global c
      c_ = c
      sleep(0.1)
      c  = c_ - 1
    
    0 讨论(0)
提交回复
热议问题