简体   繁体   English

是 Python 解包原子 w.r.t。 中断?

[英]Is Python unpacking atomic w.r.t. interrupts?

Given the following example给定以下示例

try:
    a, b = 0, 0
    for _ in range(100):
        a, b = (a+1, b+1)
except KeyboardInterrupt:
    assert a == b

could an AssertionError be thrown?可以抛出AssertionError吗? If so, is there a way to prevent it, ie to ensure that either both of a and b or none is updated on every iteration?如果是这样,有没有办法防止它,即确保每次迭代都更新ab或都不更新?


Possibly related to Is Python unpacking thread safe?可能与Python 拆包线程安全有关吗?

Within, the following example and corresponding opcode are given:其中,给出了以下示例和相应的操作码:

>>> 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        

Since there are two separate instructions for storing a and b , I would expect that no guarantees can be given whether both or none of the two instructions is executed prior to a KeyboardInterrupt .由于有两条单独的指令用于存储ab ,因此我希望无法保证这两条指令是否都在KeyboardInterrupt之前执行。

Your intuition is correct: while Python will handle the interrupt internally and re-expose it separately (so interrupts are not quite as fraught as they are in C), as noted in eg PEP 343:您的直觉是正确的:虽然 Python 将在内部处理中断并单独重新公开它(因此中断不像在 C 中那样令人担忧),如 PEP 343 中所述:

Even if you write bug-free code, a KeyboardInterrupt exception can still cause it to exit between any two virtual machine opcodes.即使您编写没有错误的代码, KeyboardInterrupt异常仍然可能导致它在任意两个虚拟机操作码之间退出。

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

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