Skip to content

xmlrpc_extended.multiprocess

Linux-only helpers for SO_REUSEPORT multi-process scale-out.

Linux only

This module raises OSError on non-Linux platforms.


create_reuseport_socket

create_reuseport_socket

create_reuseport_socket(host: str, port: int, *, backlog: int = 64) -> socket

Create a TCP socket with SO_REUSEPORT enabled.

Multiple processes may call this function with the same host and port to share the listening socket. Each call creates an independent socket file descriptor bound to the same address.

Parameters:

Name Type Description Default
host str

The interface address to bind to (e.g. "0.0.0.0" or "127.0.0.1").

required
port int

The TCP port to listen on.

required
backlog int

The OS-level accept backlog (default: 64).

64

Returns:

Type Description
socket

A bound, listening :class:socket.socket.

Raises:

Type Description
OSError

If SO_REUSEPORT is not supported on the current platform.

Source code in src/xmlrpc_extended/multiprocess.py
def create_reuseport_socket(
    host: str,
    port: int,
    *,
    backlog: int = 64,
) -> socket.socket:
    """Create a TCP socket with ``SO_REUSEPORT`` enabled.

    Multiple processes may call this function with the same *host* and *port*
    to share the listening socket.  Each call creates an independent socket
    file descriptor bound to the same address.

    Args:
        host: The interface address to bind to (e.g. ``"0.0.0.0"`` or
              ``"127.0.0.1"``).
        port: The TCP port to listen on.
        backlog: The OS-level accept backlog (default: 64).

    Returns:
        A bound, listening :class:`socket.socket`.

    Raises:
        OSError: If ``SO_REUSEPORT`` is not supported on the current platform.
    """
    if not _is_reuseport_supported():
        raise OSError("SO_REUSEPORT is not supported on this platform. Linux kernel 3.9+ is required.")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock

spawn_workers

spawn_workers

spawn_workers(worker_fn: Callable[[], None], *, num_workers: int | None = None) -> list[Process]

Spawn num_workers worker processes, each running worker_fn.

Parameters:

Name Type Description Default
worker_fn Callable[[], None]

A zero-argument callable that starts a server. Each worker should call :func:create_reuseport_socket internally so they all share the same port.

required
num_workers int | None

Number of worker processes to start. Defaults to the number of available CPU cores.

None

Returns:

Type Description
list[Process]

List of started :class:multiprocessing.Process objects. The caller

list[Process]

is responsible for joining or terminating them.

Example::

processes = spawn_workers(run_my_server, num_workers=4)
try:
    for p in processes:
        p.join()
except KeyboardInterrupt:
    for p in processes:
        p.terminate()
Source code in src/xmlrpc_extended/multiprocess.py
def spawn_workers(
    worker_fn: Callable[[], None],
    *,
    num_workers: int | None = None,
) -> list[multiprocessing.Process]:
    """Spawn *num_workers* worker processes, each running *worker_fn*.

    Args:
        worker_fn: A zero-argument callable that starts a server.  Each
            worker should call :func:`create_reuseport_socket` internally
            so they all share the same port.
        num_workers: Number of worker processes to start.  Defaults to the
            number of available CPU cores.

    Returns:
        List of started :class:`multiprocessing.Process` objects.  The caller
        is responsible for joining or terminating them.

    Example::

        processes = spawn_workers(run_my_server, num_workers=4)
        try:
            for p in processes:
                p.join()
        except KeyboardInterrupt:
            for p in processes:
                p.terminate()
    """
    if num_workers is None:
        import os

        num_workers = os.cpu_count() or 1

    processes = []
    for _ in range(num_workers):
        p = multiprocessing.Process(target=worker_fn, daemon=False)
        p.start()
        processes.append(p)
    return processes