global interpreter lock 金局解释锁, 使得同一时刻只有一个线程在cpu上执行python的字节码文件,无法将多个线程映射到各个cpu上执行.
gil会根据执行的字节码行数或cpu时间片,或io操作,会主动释放gil锁
import threading total = 0 def add(): global total for i in range(1000000): total += 1 def sub(): global total for i in range(1000000): total -= 1 if __name__ == '__main__': t1 = threading.Thread(target=add) t2 = threading.Thread(target=sub) t1.start() t2.start() t1.join() t2.join() print(total) # 并不等于0,说明不是等t1执行完了t2再执行.
日拱一卒无有尽,功不唐捐终入海