İçeriğe geç

GIL altında CPU-yoğun thread (ARCH2042)

Anahtar python.async.cpu-bound-thread-gil · Önem info · Kategori async

CPython gibi GIL kısıtlı runtime’larda CPU-yoğun iş için thread açmak hızlanma sağlamaz; thread’ler aynı anda yalnızca tek bir Python bytecode’u çalıştırır. CPU paralelliği için süreçler kullanılmalıdır.

import threading
def crunch(chunks):
threads = [threading.Thread(target=cpu_heavy, args=(c,)) for c in chunks]
for t in threads:
t.start() # GIL nedeniyle paralelleşmez
from concurrent.futures import ProcessPoolExecutor
def crunch(chunks):
with ProcessPoolExecutor() as pool:
return list(pool.map(cpu_heavy, chunks)) # gerçek paralellik

CPU-yoğun iş için thread yerine ProcessPoolExecutor veya multiprocessing kullanın.