Is the += operator thread-safe in Python?

后端 未结 8 1556
萌比男神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 13:58

    Short answer: no.

    Long answer: generally not.

    While CPython's GIL makes single opcodes thread-safe, this is no general behaviour. You may not assume that even simple operations like an addition is a atomic instruction. The addition may only be half done when another thread runs.

    And as soon as your functions access a variable in more than one opcode, your thread safety is gone. You can generate thread safety, if you wrap your function bodies in locks. But be aware that locks may be computationally costly and may generate deadlocks.

提交回复
热议问题