简体   繁体   English

序列解包是原子的吗?

[英]Is sequence unpacking atomic?

Is sequence unpacking atomic? 序列解包是原子的吗? eg: 例如:

(a, b) = (c, d)

I'm under the impression it is not. 我的印象不是。

Edit: I meant atomicity in the context of multi-threading, ie 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)

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        

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. 但是, 正常的分配总是至少有两个操作码(一个用于右手表达式,一个用于存储结果),因此在python 中一般来说,分配不是原子的。 Sequence unpacking is no different. 序列拆包也不例外。

Definitely not atomic in a multi-threaded environment, tested using the following script: 在多线程环境中绝对不是原子的,使用以下脚本进行测试:

import threading

a, b = 10, 10
finished = False
def thr():
    global finished
    while True:
        # if sequence unpacking and assignment is atomic then (a, b) will always
        # be either (10, 10) or (20, 20).  Could also just check for a != b
        if (a, b) in [(10, 20), (20, 10)]:
            print('Not atomic')
            finished = True
            break

t = threading.Thread(target=thr)
t.start()

while True:
    for i in range(1000000):
        a, b = 20, 20
        a, b = 10, 10
    if finished:
        t.join()
        break

Tested using CPython 2.6, 2.7, and 3.2. 使用CPython 2.6,2.7和3.2进行测试。 On each version this script printed 'Not atomic' and exited in well under a second. 在每个版本上,此脚本打印出“非原子”并在一秒钟内退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM