Is the += operator thread-safe in Python?

后端 未结 8 1564
萌比男神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:02

    If you actually want to make your code not thread-safe, and have good chance of "bad" stuff actually happening without you trying like ten thousand times (or one time when you real don't want "bad" stuff to happen), you can 'jitter' your code with explicit sleeps:

    def íncrement():
        global c
        x = c
        from time import sleep
        sleep(0.1)
        c = x + 1
    

提交回复
热议问题