Skip to content

redsun.compute

The pool of threads the session shares between its components, the pools of worker processes it gives each component asking for one, and the executors a component submits its calls through. Usage is in How to run background processing.

Executors

ThreadExecutor

ThreadExecutor(pool: PoolT, owner: str)

Bases: PoolExecutor[ThreadPool]

Runs one owner's calls on a shared pool of threads.

pool_type class-attribute

pool_type: type[Pool]

The kind of pool this executor submits to.

native_threads property

native_threads: int

Threads each worker's native libraries may use.

submit

submit(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> Future[R]

Run fn(*args, **kwargs) on a worker of the pool.

Raises:

Type Description
RuntimeError

If this executor has shut down.

BrokenPool

If the pool broke at start, or its workers broke.

TypeError

If the pool runs calls in worker processes and fn is a lambda, a closure, a bound method or a function defined in the script being run.

run async

run(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> R

Await the result of fn(*args, **kwargs) run on a worker.

shutdown

shutdown(
    wait: bool = True, *, cancel_futures: bool = False
) -> None

Refuse new calls, and cancel or wait for this owner's calls alone.

The callbacks of calls still running are dropped. The pool keeps serving other owners. Calls still waiting for the pool to start are not waited for.

usage

usage() -> OwnerUsage

Return the counts of this owner's calls in the pool.

ProcessExecutor

ProcessExecutor(pool: PoolT, owner: str)

Bases: PoolExecutor[ProcessPool]

Runs one owner's calls on a pool of worker processes.

A session gives each owner a pool of its own. Its usage counts a call as active once the call is handed to the standard library's pool, whether a worker runs it yet or not, so the waiting count and the longest wait cover only the time before that hand-over.

pool_type class-attribute

pool_type: type[Pool]

The kind of pool this executor submits to.

native_threads property

native_threads: int

Threads each worker's native libraries may use.

submit

submit(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> Future[R]

Run fn(*args, **kwargs) on a worker of the pool.

Raises:

Type Description
RuntimeError

If this executor has shut down.

BrokenPool

If the pool broke at start, or its workers broke.

TypeError

If the pool runs calls in worker processes and fn is a lambda, a closure, a bound method or a function defined in the script being run.

run async

run(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> R

Await the result of fn(*args, **kwargs) run on a worker.

shutdown

shutdown(
    wait: bool = True, *, cancel_futures: bool = False
) -> None

Refuse new calls, and cancel or wait for this owner's calls alone.

The callbacks of calls still running are dropped. The pool keeps serving other owners. Calls still waiting for the pool to start are not waited for.

usage

usage() -> OwnerUsage

Return the counts of this owner's calls in the pool.

Results

Future

Future()

Bases: Future[R]

A call's result, delivered by then.

cancel

cancel() -> bool

Cancel the call, unless a worker has taken it.

result

result(timeout: float | None = None) -> R

Return the result, refusing to wait without a timeout before the pool starts.

exception

exception(
    timeout: float | None = None,
) -> BaseException | None

Return the exception, refusing to wait without a timeout before the pool starts.

then

then(
    on_result: Callable[[R], object],
    on_error: Callable[[BaseException], object]
    | None = None,
) -> None

Call on_result with the result, or on_error with the exception.

The callback runs on the thread its slot marker names, else on the pool's delivery thread. A future of a pool with no delivery, or no pool, calls back in the thread that finishes the call. A cancelled call calls neither, and a failure with no on_error is logged.

BrokenPool

Bases: BrokenExecutor

Raised by a call whose pool stopped working before it could run.

WorkerCrashed

Bases: Exception

Raised by a call that was unfinished when a worker process ended.

Pools

ThreadPool

ThreadPool(
    threads: int = 1,
    *,
    native_threads: int = 1,
    initializer: Callable[[], object] | None = None,
)

Bases: Pool

Threads several executors share; with threads=0 a call runs where it is submitted.

native_threads property

native_threads: int

Threads each worker's native libraries may use.

pool_size property

pool_size: int

Worker threads.

start

start() -> None

Make the workers and send the waiting calls, once.

Raises:

Type Description
BrokenPool

If the workers cannot be made. The waiting calls fail with it too.

submit

submit(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> Future[R]

Run fn(*args, **kwargs) on a worker, counted under "<pool>".

shutdown

shutdown(
    wait: bool = True, *, cancel_futures: bool = False
) -> None

Cancel the calls waiting for start, then stop the workers.

resource classmethod

resource(
    settings: ThreadPoolSettings,
    limits: Limits,
    delivery: Delivery | None = None,
) -> Generator[ThreadPool, None, None]

Build a pool from settings, yield it unstarted, and stop it at teardown.

Teardown logs one line on the calls made and does not wait for the calls still running.

ThreadPoolSettings dataclass

ThreadPoolSettings(threads: int, native_threads: int)

How many threads a thread pool has.

threads instance-attribute

threads: int

Worker threads; 0 runs each call in the thread that submits it.

native_threads instance-attribute

native_threads: int

Threads each worker's native libraries may use.

ProcessPool

ProcessPool(
    workers: int = 1,
    *,
    priority: Priority = "normal",
    stop_timeout: float = 10.0,
    log_name: str = "redsun.workers",
)

Bases: Pool

A pool of worker processes; with workers=0 a call runs where it is submitted.

A call runs in a worker only if its function and arguments survive pickling. A function defined at module level of an importable module is sent by name; a lambda, a closure, a bound method or a function defined in the script being run is refused at submit. With workers=0 each call and its result still make a pickle round trip.

Workers start with the spawn method, so a script that starts a pool must be guarded by if __name__ == "__main__":. The workers' log records reach the session's log under log_name, from the level the redsun logger had when the pool started; a later change of that level does not reach the workers. Shutting the pool down waits for running calls at most stop_timeout seconds, then ends the workers still running, which fails their calls with BrokenPool.

A worker that ends while calls are unfinished fails every one of them with WorkerCrashed once the pool has started new workers. Replaced more than 3 times within 60 s, the pool breaks instead and refuses later calls with BrokenPool.

Parameters:

Name Type Description Default
workers int

Worker processes; 0 runs each call in the thread that submits it.

1
priority Priority

The priority the workers start at.

'normal'
stop_timeout float

Seconds shutdown waits for running calls before ending the workers.

10.0
log_name str

Name of the logger the workers' records are filed under.

'redsun.workers'

native_threads property

native_threads: int

Threads each worker's native libraries may use.

pool_size property

pool_size: int

Worker processes.

start

start() -> None

Make the workers and send the waiting calls, once.

Raises:

Type Description
BrokenPool

If the workers cannot be made. The waiting calls fail with it too.

submit

submit(
    fn: Callable[P, R], /, *args: args, **kwargs: kwargs
) -> Future[R]

Run fn(*args, **kwargs) on a worker, counted under "<pool>".

shutdown

shutdown(
    wait: bool = True, *, cancel_futures: bool = False
) -> None

Cancel the calls waiting for start, then stop the workers.

resource classmethod

resource(
    settings: ProcessPoolSettings,
    limits: Limits,
    delivery: Delivery | None = None,
    owner: str = "<pool>",
) -> Generator[ProcessPool, None, None]

Build a pool from settings, yield it unstarted, and stop it at teardown.

Teardown logs one line on the calls made, then waits for the running calls as shutdown does.

ProcessPoolSettings dataclass

ProcessPoolSettings(
    processes: int,
    native_threads: int = 1,
    priority: Priority = "normal",
)

How many processes a process pool has, and the priority they start at.

processes instance-attribute

processes: int

Worker processes; 0 runs each call in the thread that submits it.

native_threads class-attribute instance-attribute

native_threads: int = 1

Threads each worker's native libraries may use.

priority class-attribute instance-attribute

priority: Priority = 'normal'

How much processor time the workers get against the rest of the system.

Limits

Limits(switch_interval_ms: float | None = None)

Native thread limits, applied once and restored at shutdown.

apply

apply(native_threads: int) -> None

Limit the native thread pools of the loaded libraries, on the first call only.

Call it from the main thread.

restore

restore() -> None

Put back what apply changed; a second call does nothing.

initializer staticmethod

initializer(native_threads: int) -> Callable[[], object]

Return what each pool thread runs to apply the limit in itself.

Counts

OwnerUsage dataclass

OwnerUsage(
    queued: int,
    active: int,
    completed: int,
    failed: int,
    longest_idle: float,
    crashed: int = 0,
)

What one owner's calls did in a pool.

A ProcessExecutor counts a call as active once it hands the call to the standard library's pool, which may still hold it in its own queue until a worker is free. Its queued counts the calls waiting for the pool to start or for that hand-over, and longest_idle covers only the wait before the hand-over.

queued instance-attribute

queued: int

Calls waiting for a worker.

active instance-attribute

active: int

Calls running.

completed instance-attribute

completed: int

Calls that returned.

failed instance-attribute

failed: int

Calls that raised.

longest_idle instance-attribute

longest_idle: float

Seconds a call waited for a worker, the longest so far.

crashed class-attribute instance-attribute

crashed: int = 0

Calls that failed because a worker process ended.

Configuration

Preset module-attribute

Preset = Literal['latency', 'balanced', 'throughput']

How the compute cores are split between pool threads and native threads.

Priority module-attribute

Priority = Literal['low', 'normal', 'high']

How much processor time worker processes get against the rest of the system.

ComputeSettings

Bases: TypedDict

The compute section a session class declares, key by key.

preset instance-attribute

preset: Preset

How the compute cores are split between threads and native libraries.

cores instance-attribute

cores: int

Cap on the compute cores; default: the physical cores less reserve.

reserve instance-attribute

reserve: int

Physical cores kept free for the window's thread; default: 1.

switch_interval_ms instance-attribute

switch_interval_ms: float | None

Interpreter thread switch interval in milliseconds; None leaves it alone.

processes instance-attribute

processes: int

Worker processes of each process pool; default: the session's share of the compute cores.

priority instance-attribute

priority: Priority

How much processor time worker processes get against the rest of the system.