Multiprocessing.Pool
suggest changeThe simple answer, when asking how to use threads in Python, is: “Don’t. Use processes, instead.” The multiprocessing module lets you create processes with similar syntax to creating threads, but I prefer using their convenient Pool object.
Using the code that David Beazley first used to show the dangers of threads against the GIL, we’ll rewrite it using multiprocessing.Pool:
David Beazley’s code that showed GIL threading problems
Re-written using multiprocessing.Pool
import multiprocessing
import time
def countdown(n):
while n > 0:
n -= 1
COUNT = 10000000
start = time.time()
with multiprocessing.Pool as pool:
pool.map(countdown, [COUNT/2, COUNT/2])
pool.close()
pool.join()
end = time.time()
print(end-start)
Instead of creating threads, this creates new processes. Since each process is its own interpreter, there are no GIL collisions. multiprocessing.Pool will open as many processes as there are cores on the machine, though in the example above, it would only need two. In a real-world scenario, you want to design your list to have at least as many items as there are processors on your machine. The Pool will run the function you tell it to run with each argument, up to the number of processes it creates. When the function finishes, any remaining functions in the list will be run on that process.
with multiprocessing.Pool as pool does not call Pool. On Python 3.14.6 that line raises TypeError. The usual form is with multiprocessing.Pool() as pool. In Python 3, COUNT/2 is the float 5000000.0. On Windows and macOS the default start method is spawn, so this pool also needs to be created under if __name__ == "__main__". The with statement calls terminate() when the block ends, which stops the worker processes. The sample still calls close() and join() before that exit. David Beazley’s original listing under the previous heading is not on the page. The sample was not run.