multiprocessing Pool Maps CPU Bound Work

Fan out CPU-bound work with multiprocessing Pool, using map, starmap, and imap_unordered while the main process stays responsive.

PythonResilience

Code

pythonsnippet
29 lines
from multiprocessing import Pool


def scale(pair: tuple[int, int]) -> tuple[int, int]:
    base, factor = pair
    return base, base * factor


def main() -> None:
    with Pool(processes=2) as pool:
        # map:一个参数序列,按输入顺序返回
        print('map:', pool.map(abs, [-4, 2, -9]))

        # starmap:每个元素解包成多个参数
        print('starmap:', pool.starmap(pow, [(2, 5), (3, 3), (5, 2)]))

        # imap_unordered:完成顺序不保证,收集后再排序
        pairs = [(1, 10), (2, 20), (3, 30)]
        print('unordered:', sorted(pool.imap_unordered(scale, pairs)))

        # apply_async:单个任务,get 时阻塞取结果
        job = pool.apply_async(sum, ([1, 2, 3],))
        print('single job:', job.get(timeout=5))

    print('pool closed cleanly')


if __name__ == '__main__':
    main()

What the code does

The working surface is the functions scale and main — everything else is wiring.

The import line is the dependency contract: Pool comes from multiprocessing and nothing else.

Watch out for

  • Dependency check: multiprocessing — not built-in, must be present in the project.

Applying it

Entry signature: def scale(pair: tuple[int, int]) -> tuple[int, int]

The demo output is labeled (map:, starmap:, unordered:), so every printed line maps back to its originating operation.

Statements that matter

def scale(pair: tuple[int, int]) -> tuple[int, int]:
    base, factor = pair
    return base, base * factor

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `multiprocessing`, which the package manager must provide.