一文搞懂Python GIL:为什么多线程反而更慢
Lisa Tan | 2026-08-19T10:23:00 | Python, AI
深入理解Python GIL机制,以及什么时候该用多线程、多进程、asyncio
# 一文搞懂Python GIL:为什么多线程反而更慢 写了个多线程跑CPU密集任务,结果比单线程还慢。查了半天发现是GIL的锅。 ## GIL是什么 Global Interpreter Lock,CPython的全局解释器锁。同一时刻只允许一个线程执行Python字节码。 ```python import threading import time counter = 0 def count_up(): global counter for _ in range(10000000): counter += 1 # 单线程 start = time.time() count_up() print("单线程: {:.2f}s".format(time.time() - start)) # 约0.8s # 多线程(并不会更快!) counter = 0 t1 = threading.Thread(target=count_up) t2 = threading.Thread(target=count_up) start = time.time() t1.start() t2.start() t1.join() t2.join() print("多线程: {:.2f}s".format(time.time() - start)) # 约1.5s,更慢了! ``` ## 什么时候用什么 | 场景 | 方案 | 原因 | |------|------|------| | CPU密集 | multiprocessing | 多进程绕过GIL | | IO密集 | threading | GIL在IO时释放 | | 高并发IO | asyncio | 协程更轻量 | ```python # CPU密集用多进程 from multiprocessing import Pool def heavy_compute(n): return sum(i * i for i in range(n)) with Pool(4) as pool: # 真正的并行,4个CPU核心同时跑 results = pool.map(heavy_compute, [10000000] * 4) ``` 记住:**CPU密集用进程,IO密集用线程/协程**。Python 3.13开始可以禁用GIL了,未来可期。