Python 变量赋值是原子的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2291069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is Python variable assignment atomic?
提问by jldupont
Let's say I am using a signal
handler for handling an interval timer.
假设我正在使用signal
处理程序来处理间隔计时器。
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-stablestate)
我可以设置SomeGlobalVariable
而不用担心,在一种不太可能的情况下,在设置时SomeGlobalVariable
(即 Python VM 正在执行字节码来设置变量),信号处理程序中的赋值会破坏某些东西吗?(即亚稳态)
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)
(也许我想得太“低级”了,这一切都在 Python 中解决了......来自嵌入式系统背景,我不时有这些冲动)
采纳答案by Alex Martelli
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).
对简单变量的简单分配是“原子”AKA 线程安全(复合分配,例如+=
对项目或对象属性的分配不需要,但您的示例是对简单变量的简单分配,尽管是全局变量,因此是安全的)。
回答by Eloff
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.
复合赋值涉及三个步骤:读-更新-写。如果在读取发生之后但在写入之前运行另一个线程并将新值写入该位置,则这是一种竞争条件。在这种情况下,一个陈旧的值正在被更新和写回,这将破坏其他线程写入的任何新值。在 Python 中,任何涉及执行单字节代码的东西都应该是原子的,但是复合赋值不符合这个标准。使用锁。