序列拆包是原子的吗? [英] Is sequence unpacking atomic?
问题描述
序列解包是原子的吗?例如:
Is sequence unpacking atomic? e.g.:
(a, b) = (c, d)
我对它的印象不是.
我的意思是在多线程上下文中使用原子性,即整个语句是否像原子一样是不可分割的.
I meant atomicity in the context of multi-threading, i.e. whether the entire statement is indivisible, as atoms used to be.
推荐答案
这是一项操作;在应用左手赋值之前先评估右手表达式:
It is one operation; the right-hand expression is evaluated before the left-hand assignment is applied:
>>> a, b = 10, 20
>>> a, b
(10, 20)
>>> b, a = a, b
>>> a, b
(20, 10)
>>> a, b = a*b, a/b
>>> a, b
(200, 2)
或者,如果您正在谈论多线程环境,则该分配是 not 原子的;解释器使用单个操作码评估一个元组分配,但是使用单独的操作码将结果存储到每个受影响的变量中:
Or, if you are talking about multi-threaded environments, then the assignment is not atomic; the interpreter evaluates a tuple assignment with a single opcode, but uses separate opcodes to then store the results into each affected variable:
>>> def t(self): a,b=20,20
...
>>> dis.dis(t)
1 0 LOAD_CONST 2 ((20, 20))
3 UNPACK_SEQUENCE 2
6 STORE_FAST 1 (a)
9 STORE_FAST 2 (b)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
但是,正常分配总是至少是两个操作码(一个用于右侧表达式,一个用于存储结果),因此通常在python 中使用分配不是原子的.序列拆包没有什么不同.
However, normal assigment is always going to be at least two opcodes (one for the right-hand expression, one for storing the result), so in python in general assigment is not atomic. Sequence unpacking is no different.
这篇关于序列拆包是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!