python的原子操作

2020年6月5日 / 274次阅读 / Last Modified 2020年6月5日
多线程

python编译器会将代码编译为bytecode,对于python而言,每一行bytecode都是原子操作。

A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via sys.setswitchinterval(). Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program.

In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are.

下面这些操作是原子的:

L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()

下面这些不是原子的:

i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1

关于 i = i+1不是原子操作,请看线程不安全一例。

关于这部分内容的官方链接:https://docs.python.org/3.5/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe

When in dount, use mutex!

-- EOF --

本文链接:https://www.pynote.net/archives/2050

留言区

《python的原子操作》有2条留言

电子邮件地址不会被公开。 必填项已用*标注

  • 麦新杰

    在python中调用so库,如果多个线程都进入了so库中的代码呢? [回复]

  • 麦新杰

    C语言的原子操作,就是一行汇编代码,或一条不可再细分的机器码。 [回复]


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top