Is the += operator thread-safe in Python?

后端 未结 8 1584
萌比男神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条回答
  •  猫巷女王i
    2020-11-27 14:04

    Are you sure that the functions increment and decrement execute without any error?

    I think it should raise an UnboundLocalError because you have to explicitly tell Python that you want to use the global variable named 'c'.

    So change increment ( also decrement ) to the following:

    def increment():
        global c
        c += 1
    

    I think as is your code is thread unsafe. This article about thread synchronisation mechanisms in Python may be helpful.

提交回复
热议问题