GitHub

Parallel effects

fx.on_thread runs an effect as a run of its own on another thread: on free-threaded Python, CPU-heavy effects use several cores. What it costs and when it pays.

Every fiber of a run takes turns on the run's thread (see Threads and throughput), so two CPU-heavy fibers of one run never compute at the same time. fx.on_thread(eff) runs eff as the root fiber of a run of its own, on a new thread, and takes on its result: its value, its typed failure or its defect. Effects under on_thread go in parallel with the caller and with each other on free-threaded Python (3.14t). On the GIL build they still take turns, at bytecode boundaries instead of fiber steps, so the caller's run keeps serving its other fibers while one computes, as with fx.blocking.

on_thread.py
import threading

import pyfect as fx


class Region(fx.Tag[str]):
    pass


@fx.fn
def summarize(rows: int):
    # An effect of many small steps: it can't be one fx.blocking call.
    region = yield from Region()
    total = 0
    for i in range(rows):
        total += yield from fx.sync(lambda i=i: i % 7)
    return region, total, threading.get_ident()


@fx.gen
def program():
    jobs = [fx.on_thread(summarize(10_000)) for _ in range(4)]
    results = yield from fx.all(*jobs, concurrency=4)
    threads = {thread for _, _, thread in results}
    print("results:", [(region, total) for region, total, _ in results])
    print("any on the caller's thread:", threading.get_ident() in threads)


fx.run_blocking(program.pipe(fx.provide_service(Region, "eu")))

The effect sees the caller's services. Interrupting the caller interrupts the effect on its own run and waits for its finalizers, as interrupting a forked fiber does, so a timeout or a race around on_thread cleans up what the effect opened. What the effect forks and leaves running goes on in the background once it ends, as after fx.run_blocking.

interrupt.py
import pyfect as fx


@fx.gen
def crunch():
    yield from fx.sleep("10 millis").forever()


@fx.gen
def program():
    # The timeout interrupts the effect on the other thread and waits for its
    # finalizer before it fails.
    work = fx.on_thread(crunch.ensuring(fx.sync(lambda: print("cleaned up on the worker thread"))))
    ex = yield from work.timeout("50 millis").exit()
    print("exit:", type(ex).__name__)


fx.run_blocking(program)

fx.blocking, fx.on_thread or a process

  • A plain function, however heavy: fx.blocking(f). It already runs on a pool thread, in parallel on 3.14t, and costs less to start. Interrupting it abandons the thread.
  • An effect of many steps (a loop of fx.sync calls, a stream, a parser written with effects): fx.on_thread(eff). It can be interrupted, and its finalizers run.
  • Parallel work on the GIL build: a ProcessWorker from workers, or one process per core.

What it measured

benchmarks/parallel.py runs N copies of the same work with concurrency=N. "Pure" is one pure-Python function (about 100 ms); "steps" is an effect of 100,000 fx.sync steps. The rate is N times one task's time alone over the fan-out's time: 1.0x is no faster than one at a time. Best of three, on an 18-core Apple M-series machine that other jobs were also using, so read the ratios, not the milliseconds:

WorkN3.14 inline3.14 on_thread3.14t inline3.14t blocking3.14t on_thread
pure41.04x0.97x1.01x2.87x3.38x
pure81.27x1.15x0.97x4.52x4.20x
steps41.04x1.05x1.09xn/a1.58x
steps80.97x0.92x1.11xn/a2.57x

On the GIL build nothing runs faster, and on_thread costs a few percent. On 3.14t a pure function scales the same through either. An effect of many steps scales, but less than a pure function: every step touches objects all threads share (the runtime's classes, methods and constants), and free-threaded CPython keeps their reference counts with atomic operations that the cores fight over. A plain thread calling fx.run_blocking scales no better.

Starting and finishing a hand-off, from asking to the work starting and from the work ending to the caller running again, p50 / p95 in milliseconds:

3.14 unloaded3.14t unloaded3.14t, a busy thread per core
blocking start0.03 / 0.070.01 / 0.040.03 / 0.13
blocking finish0.03 / 0.070.01 / 0.060.07 / 1.2
on_thread start0.05 / 0.120.07 / 0.140.08 / 0.14
on_thread finish0.06 / 0.140.03 / 0.090.25 / 1.0

on_thread starts a thread per call, so it suits work of a millisecond or more. With every core busy, a wake-up waits for the OS to give the waiting thread a core: on 3.14t the finish's p95 went from about 1 ms (the table, N=4) to 15 ms for on_thread and 25 ms for blocking (a run with N=8), while on the GIL build either waits for the GIL behind every busy thread, with a p50 of 30 to 130 ms.