is python variable assignment atomic?

2019-01-23 13:08发布

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

def _aHandler(signum, _):
  global SomeGlobalVariable
  SomeGlobalVariable=True

Can I set SomeGlobalVariable without worrying that, in an unlikely scenario that whilst setting SomeGlobalVariable (i.e. the Python VM was executing bytecode to set the variable), that the assignment within the signal handler will break something? (i.e. meta-stable state)

Update: I am specifically interested in the case where a "compound assignment" is made outside of the handler.

(maybe I am thinking too "low level" and this is all taken care of in Python... coming from an Embedded Systems background, I have these sorts of impulses from time to time)

2条回答
放我归山
2楼-- · 2019-01-23 13:44

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.

查看更多
干净又极端
3楼-- · 2019-01-23 13:55

Simple assignment to simple variables is "atomic" AKA threadsafe (compound assignments such as += or assignments to items or attributes of objects need not be, but your example is a simple assignment to a simple, albeit global, variable, thus safe).

查看更多
登录 后发表回答