Is Python variable assignment atomic?

前端 未结 3 1812
小蘑菇
小蘑菇 2020-12-05 09:46

Let\'s say I am using a signal handler for handling an interval timer.

def _aHandler(signum, _):
  global SomeGlobalVariable
  SomeGlobalVariabl         


        
3条回答
  •  日久生厌
    2020-12-05 10:40

    Compound assignment involves three steps: read-update-write. This is a race condition if another thread is run and writes a new value to the location after the read happens, but before the write. In this case a stale value is being updated and written back, which will clobber whatever new value was written by the other thread. In Python anything that involves the execution of a single byte code SHOULD be atomic, but compound assignment does not fit this criteria. Use a lock.

提交回复
热议问题