1. GIL (Global Interpreter lock)可以避免多个线程同时执行字节码。
import threading
lock = threading.Lock()
n = [0]
def foo():
with lock:
n[0] = n[0] + 1
n[0] = n[0] + 1
threads = []
for i in range(5000):
t = threading.Thread(target=foo)
threads.append(t)
for t in threads:
t.start()
print(n)
2. 使用dis操作来分析字节码
import dis
def update_list(l):
l[0] = 1
dis.dis(update_list)
输出为:
4 0 LOAD_CONST 1 (1)
2 LOAD_FAST 0 (l)
4 LOAD_CONST 2 (0)
6 STORE_SUBSCR
8 LOAD_CONST 0 (None)
10 RETURN_VALUE
“STORE_SUBSCR”,可见只有单节字码操作。
def incr_list(l):
l[0] += 1
dis.dis(incr_list)
输出为:
2 0 LOAD_FAST 0 (l)
2 LOAD_CONST 1 (0)
4 DUP_TOP_TWO
6 BINARY_SUBSCR
8 LOAD_CONST 2 (1)
10 INPLACE_ADD
12 ROT_THREE
14 STORE_SUBSCR
16 LOAD_CONST 0 (None)
18 RETURN_VALUE
可见需要多个字节码操作,有可能在线程执行过程中切到其他线程。