ProcessPoolExecutor Runs CPU Work In Parallel

Fan out CPU-bound prime counting across a ProcessPoolExecutor, map inputs to workers, and keep the Windows-safe main guard.

PythonResilience

Code

pythonsnippet
29 lines
from concurrent.futures import ProcessPoolExecutor


def count_primes(limit: int) -> int:
    if limit < 3:
        return 0
    sieve = bytearray([1]) * limit
    sieve[0:2] = bytearray([0, 0])
    for value in range(2, int(limit ** 0.5) + 1):
        if sieve[value]:
            start = value * value
            count = ((limit - 1 - start) // value) + 1
            sieve[start:limit:value] = bytearray([0]) * count
    return sum(sieve)


def main() -> None:
    limits = [100_000, 200_000, 400_000, 800_000]
    with ProcessPoolExecutor(max_workers=4) as pool:
        counts = list(pool.map(count_primes, limits))

    for limit, count in zip(limits, counts):
        print(limit, 'primes:', count)

    print('main process finished')


if __name__ == '__main__':
    main()

How it works

ProcessPoolExecutor Runs CPU Work In Parallel reduces to the functions count_primes and main.

for value in range(2, int(limit ** 0.5) + 1) is the loop that carries the per-item work. ProcessPoolExecutor are the only symbols borrowed from concurrent — the coupling is explicit and narrow.

What to watch for

  • External dependency: concurrent — install it before running the snippet.

Using it

Entry signature: def count_primes(limit: int) -> int

The demo output is labeled (main process finished), so every printed line maps back to its originating operation.

Key statements

def main() -> None:
    limits = [100_000, 200_000, 400_000, 800_000]
    with ProcessPoolExecutor(max_workers=4) as pool:
        counts = list(pool.map(count_primes, limits))
    for limit, count in zip(limits, counts):
        print(limit, 'primes:', count)
    print('main process finished')

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `concurrent`. Without it the snippet will not load.