Back to questions
MiddleCodeCommon
Why does this threaded CPU loop get no speedup?
This runs two threads of pure-Python counting, but is no faster than one.
import threading
def count():
x = 0
for _ in range(10**7): x += 1
t1 = threading.Thread(target=count)
t2 = threading.Thread(target=count)
t1.start(); t2.start(); t1.join(); t2.join()Determine why there is no speedup and how to fix it.
The two threads are no faster than sequential — often slower, from GIL contention — because count is pure-Python CPU work and the GIL lets only one thread run bytecode at a time. To parallelize, use multiprocessing.Process or a ProcessPoolExecutor.
- Believing threads give CPU parallelism in CPython
- Thinking the GIL only affects I/O, not CPU loops
- Expecting a longer loop to overcome the GIL
- Why does the GIL not hurt I/O-bound threaded code the same way?
- How does
multiprocessingachieve real CPU parallelism that threads cannot?