Billiard: Improved Python Multiprocessing

4.2.4 · active · verified Sat Mar 28

billiard is a robust fork of the Python 2.7 `multiprocessing` package, actively maintained by the Celery project. It provides numerous improvements and bugfixes over the standard library's `multiprocessing` module, offering enhanced process-based parallelism for Python applications. It aims to address specific challenges and performance bottlenecks, particularly in distributed task queue systems like Celery, where it serves as a core dependency. The library is under active development with a consistent release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and use a process pool with `billiard.Pool` to execute a function across multiple processes. The `if __name__ == '__main__':` guard is essential for proper functioning, especially on Windows and with certain start methods, to prevent infinite process spawning.

import os
from billiard import Pool

def worker_function(x):
    """A simple function to be executed by pool workers."""
    print(f"Worker PID {os.getpid()}: Processing {x}")
    return x * x

if __name__ == '__main__':
    # It's crucial to use the if __name__ == '__main__': guard
    # especially on Windows or when using 'spawn' start methods.
    print(f"Main process PID: {os.getpid()}")
    
    with Pool(processes=3) as pool:
        # Map the worker_function to a list of inputs
        results = pool.map(worker_function, range(5))
        print(f"Results: {results}")

    # Alternatively, you can explicitly close and join the pool
    # pool = Pool(processes=2)
    # async_result = pool.apply_async(worker_function, (10,))
    # print(f"Async result: {async_result.get()}")
    # pool.close()
    # pool.join()

view raw JSON →