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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `multiprocessing`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.