GIL
# GIL:Global Interpreter Lock,全局解释器锁
# 它让python在同一时刻只有一个线程运行在一个CPU上去执行字节码,无法发挥多核的优势
# 但它并不是线程安全的
import threading
counter = 0
def inc():
global counter
for i in range(1000000):
counter += 1
def dec():
global counter
for i in range(1000000):
counter -= 1
# gil并不是一直占有锁,它会在某些条件下释放,例如,时间片、执行代码的行数或者遇到IO操作等
thread1 = threading.Thread(target=inc)
thread2 = threading.Thread(target=dec)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
# 打印出的值是随机的
print(counter)
大约 11 分钟