silk.concurrency.thread_pool.
A work-stealing pool of native threads that runs fibers in parallel.
When to use#
Call
ThreadPool.maketo start the worker threads.Call
Pool.blockon a normal thread to run a program on the pool.In a fiber, start more fibers with
Pool.fork, and wait for one withPoolFiber.joinorPoolFiber.await.Stop a fiber and get its final outcome with
PoolFiber.interrupt.Wait for the first of two fibers with
PoolFiber.awaitEither, or keep the first result and cancel the other withPoolFiber.race.Bound a wait in a fiber with
Pool.timeout.
Details#
A pool fiber is a Transferable lazy effect, packaged with Execution.makeTransferable. Thus
a fiber can start on one worker, park, and continue on a different worker. Its outcome is the
same Outcome that silk.concurrency.fiber uses: success, typed failure, or Cancelled.
A ready fiber goes on one shared ready list. An idle worker moves a batch of ready fibers into
its own WorkDeque. A worker with nothing to do steals from the deques of the other workers,
and then sleeps on a Parker. When a parked fiber wakes, it goes back on the ready list and a
sleeping worker wakes. Thus no worker spins.
PoolFiber.interrupt marks the fiber for cancellation and waits for it. A parked fiber is
cancelled by the next worker that takes it: the worker drops the parked frames, which runs their
Drop cleanup, and the outcome is Cancelled. A running fiber is cancelled the next time it
parks, for example in Pool.yieldNow or PoolFiber.join.
Each fiber body gets its own PoolTask provider, which holds the fiber's deadlines.
Pool.timeout arms one, as Effect.timeout does under a Scheduler. When it passes while
the fiber is parked inside the timed effect, the pool interrupts the fiber there, and the call
fails with TimeoutError. Idle workers sleep only until the earliest deadline.
A Pool is a small Transferable handle that fibers capture to fork more fibers. The
ThreadPool owns the threads. Dropping it stops and joins each worker, and cancels the
fibers that are not finished.
Errors#
ThreadPool.makefails withSpawnErrororOutOfMemoryError.Pool.fork,PoolFiber.awaitEitherandPoolFiber.racefail withOutOfMemoryError.Pool.blockandPoolFiber.joinraise the typed failure of the fiber unchanged, orCancelled.PoolFiber.awaitreturns them as data.Pool.timeoutfails withTimeoutErrorwhen its deadline passes first.
Gotchas#
Fiber bodies, results and failures must be
Transferableand'static.In a fiber, wait for anything other than a
PoolFiberwithExecution.parkTransferable. A call that blocks the native thread, such asPool.block, holds up a whole worker.Call the waiting operations of
PoolFiberandPool.yieldNowonly from inside a pool fiber.A fiber that never parks runs to the end, even after an interrupt or a timeout.
The pool uses the system allocator for its own storage, not the
Allocatorof the caller.
Examples#
Sum two halves in parallel#
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.concurrency.fiber { Cancelled }
import silk.concurrency.thread_native { SpawnError }
import silk.concurrency.thread_pool { Pool, ThreadPool }
effect fn sumRange(from: i64, to: i64) -> i64 {
let mut total: i64 = 0
let mut at = from
while at < to {
total = total + at
at = at + 1
}
return total
}
// Runs the low half as a new fiber, and the high half in this fiber.
effect fn both(pool: Pool) -> i64
! OutOfMemoryError | Cancelled {
let low = run pool.fork(sumRange(0, 500))
let high = run sumRange(500, 1001)
let lowValue = run low.join()
return lowValue + high
}
effect fn program() -> i32
! OutOfMemoryError | SpawnError | Cancelled {
let mut allocator = Allocator.systemAllocatorProvider()
let threads = run ThreadPool.make(4) |> Effect.provideMut<Allocator>(&mut allocator)
let pool = threads.pool()
let value = run pool.block(both(pool.clone()))
if value != 500500 {
return 1
}
return 0
}
effect fn failed<E>(error: E) -> i32 {
drop error
return 1
}
pub fn main() -> i32 {
return run Effect.catchAll(program(), failed)
}Stop a wait after one millisecond#
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect, TimeoutError }
import silk.core.result { Result }
import silk.concurrency.execution { Execution, TransferableWake }
import silk.concurrency.fiber { Cancelled }
import silk.concurrency.thread_native { SpawnError }
import silk.concurrency.thread_pool { Pool, PoolTask, ThreadPool }
// Parks and drops its Wake, so nothing ever resumes it.
effect fn forever() -> i32 {
run Execution.parkTransferable(|wake: TransferableWake| -> () {
drop wake
return ()
})
return 1
}
effect fn waitBriefly(pool: Pool) -> i32
! OutOfMemoryError ? &mut PoolTask {
let stuck = run pool.fork(forever())
let waited = run Effect.result(Pool.timeout(stuck.join(), 1000000))
return match move waited {
Result<i32, Cancelled | TimeoutError>.Failure { error } => 0
Result<i32, Cancelled | TimeoutError>.Success { value } => 1
}
}
effect fn program() -> i32
! OutOfMemoryError | SpawnError | Cancelled {
let mut allocator = Allocator.systemAllocatorProvider()
let threads = run ThreadPool.make(2) |> Effect.provideMut<Allocator>(&mut allocator)
let pool = threads.pool()
return run pool.block(waitBriefly(pool.clone()))
}
effect fn failed<E>(error: E) -> i32 {
drop error
return 1
}
pub fn main() -> i32 {
return run Effect.catchAll(program(), failed)
}Interrupt a fiber that waits forever#
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.concurrency.execution { Execution, TransferableWake }
import silk.concurrency.fiber { Cancelled, Outcome }
import silk.concurrency.thread_native { SpawnError }
import silk.concurrency.thread_pool { Pool, ThreadPool }
// Parks and drops its Wake, so nothing ever resumes it.
effect fn forever() -> i32 {
run Execution.parkTransferable(|wake: TransferableWake| -> () {
drop wake
return ()
})
return 1
}
effect fn stopOne(pool: Pool) -> i32
! OutOfMemoryError {
let stuck = run pool.fork(forever())
let outcome = run stuck.interrupt()
let Outcome<i32, never> { value } = move outcome
return match move value {
Cancelled {} => 0
_ => 1
}
}
effect fn program() -> i32
! OutOfMemoryError | SpawnError | Cancelled {
let mut allocator = Allocator.systemAllocatorProvider()
let threads = run ThreadPool.make(2) |> Effect.provideMut<Allocator>(&mut allocator)
let pool = threads.pool()
return run pool.block(stopOne(pool.clone()))
}
effect fn failed<E>(error: E) -> i32 {
drop error
return 1
}
pub fn main() -> i32 {
return run Effect.catchAll(program(), failed)
}Import as ThreadPool with import silk.concurrency.thread_pool { ThreadPool }.
Public declarations: 6.
PoolFiber#
pub struct PoolFiber<A, E>The handle of one pool fiber, which gives back its outcome and can interrupt it.
Details#
A handle is Transferable when A and E are. It has one observer: await and join
consume it. Dropping it detaches the fiber, which still runs.
Implementation PoolFiber<A, E>#
impl<A, E> PoolFiber<A, E>Method await#
pub effect fn await(self: Self) -> Outcome<A, E>Parks the calling fiber until this fiber ends, then returns its success, typed failure, or cancellation as data.
Gotchas#
Only a pool fiber can await. An await from any other place is a fatal state trap.
Method join#
pub effect fn join(self: Self) -> A ! E | CancelledParks the calling fiber until this fiber ends, then returns its success value.
Details#
The typed failure of the fiber is raised unchanged. Cancellation raises Cancelled.
Gotchas#
Only a pool fiber can join. A join from any other place is a fatal state trap.
Method interrupt#
pub effect fn interrupt(self: Self) -> Outcome<A, E>Cancels this fiber unless it already finished, waits until it has stopped, and returns its final outcome.
Details#
A parked fiber is cancelled by the next worker that takes it. A running fiber is cancelled
the next time it parks. Cancellation drops the fiber's frames, which runs their Drop
cleanup, and the outcome is Cancelled. A fiber that finished first keeps its success or
typed failure.
Gotchas#
Only a pool fiber can interrupt. An interrupt from any other place is a fatal state trap.
A fiber that never parks runs to the end, so the interrupt waits for that.
Method awaitEither#
pub effect fn awaitEither<B, F>(self: Self, other: PoolFiber<B, F>) -> PoolFirstLeft<A, E, B, F> | PoolFirstRight<A, E, B, F>
! OutOfMemoryErrorParks the calling fiber until the first of two fibers ends, and returns its outcome with the other fiber.
When to use#
Use awaitEither to act on whichever fiber ends first. Use race when the other fiber
should then be cancelled.
Details#
If both had already ended before the call, self wins. The other fiber is returned
unobserved and possibly still running, so the caller can await, interrupt, or drop it. A
failure or a cancellation of the winner is data in its Outcome.
Errors#
Fails with OutOfMemoryError when the shared wait cannot be allocated. It allocates only when
neither fiber has ended yet.
Gotchas#
Only a pool fiber can wait. A wait from any other place is a fatal state trap.
Method race#
pub effect fn race(self: Self, other: PoolFiber<A, E>) -> A ! E | Cancelled | OutOfMemoryErrorParks the calling fiber until the first of two fibers ends, cancels the other, and returns the first result.
When to use#
Use race to take whichever of two equivalent computations ends first, such as two replicas
of one request.
Details#
The first fiber to end wins, whatever its outcome: its typed failure is raised unchanged, and
a cancelled winner raises Cancelled. The other fiber is cancelled with interrupt before
race returns, so its cleanup has finished. If both had already ended before the call,
self wins.
Errors#
Fails with OutOfMemoryError when the shared wait cannot be allocated.
Gotchas#
Only a pool fiber can race. A race from any other place is a fatal state trap.
PoolFirstLeft#
pub struct PoolFirstLeft<A, E, B, F>The first fiber of a PoolFiber.awaitEither ended first.
Field outcome#
pub outcome: Outcome<A, E>The outcome of the first fiber.
Field other#
pub other: PoolFiber<B, F>The second fiber, unobserved and possibly still running.
PoolFirstRight#
pub struct PoolFirstRight<A, E, B, F>The second fiber of a PoolFiber.awaitEither ended first.
Field other#
pub other: PoolFiber<A, E>The first fiber, unobserved and possibly still running.
Field outcome#
pub outcome: Outcome<B, F>The outcome of the second fiber.
PoolTask#
pub service PoolTaskThe deadlines of the calling pool fiber, which Pool.timeout arms.
Details#
Every pool fiber gets its own provider, so its body can require &mut PoolTask. It works like
the deadline operations of Scheduler: when a deadline passes while the fiber is parked inside
the interruptible boundary that Intrinsic.interruptibleEffect opened for its token, the pool
interrupts the fiber with that token. A deadline that passes while the fiber runs interrupts it
at its next park inside the boundary. The pool measures time on the OS monotonic clock.
Operation armDeadlineAfter#
effect fn armDeadlineAfter(howLong: u64) -> usize ? &mut PoolTaskArms a deadline howLong nanoseconds from now for the calling fiber, and returns its token,
which is never 0. The pool removes a deadline once it fires.
Operation disarmDeadline#
effect fn disarmDeadline(token: usize) -> () ? &mut PoolTaskDisarms a deadline the calling fiber armed. A deadline that already fired is ignored.
Pool#
pub struct PoolA handle to a running pool, which fibers capture to fork more fibers.
Details#
A handle is Transferable and Concurrent. It does not keep the worker threads running:
once the ThreadPool that made it is dropped, a forked fiber is cancelled before it starts.
Implementation Pool#
impl PoolMethod fork#
pub effect<'env> fn fork<
'env,
A: 'static + Transferable,
E: 'static + Transferable,
F: once Effect<'static; A ! E ? &mut PoolTask> + Intrinsic.Detached + Transferable
>(self: &Self, task: F) -> PoolFiber<A, E> ! OutOfMemoryErrorStarts task as a new pool fiber and returns the handle that awaits it.
Details#
The fiber is ready at once. It can start on any worker before this call returns. Its typed
failure E is kept in its outcome, for PoolFiber.await or PoolFiber.join.
Gotchas#
The body, its result and its failure must be Transferable and 'static. Dropping the
returned handle does not cancel the fiber.
Method block#
pub effect<'env> fn block<
'env,
A: 'static + Transferable,
E: 'static + Transferable,
F: once Effect<'static; A ! E ? &mut PoolTask> + Intrinsic.Detached + Transferable
>(self: &Self, task: F) -> A ! OutOfMemoryError | E | CancelledRuns task on the pool and blocks the calling thread until it ends.
Details#
The typed failure of the fiber is raised unchanged. A fiber cancelled by the pool's drop
raises Cancelled.
Gotchas#
Calling it from a pool fiber blocks that fiber's worker for the whole wait.
Method clone#
pub fn clone(self: &Self) -> PoolReturns another handle to the same pool.
Associated function yieldNow#
pub effect fn yieldNow() -> ()Lets the other ready fibers run before the calling fiber continues.
Details#
The calling fiber goes to the end of the ready list. An interrupt requested while it ran cancels it here.
Gotchas#
Only a pool fiber can yield. A yield from any other place is a fatal state trap.
Associated function timeout#
pub effect fn timeout<'env, A, E, ?R>(
body: once Effect<'env; A ! E ? R>,
howLong: u64
) -> A ! E | TimeoutError ? R | &mut PoolTaskRuns body in the calling fiber, and stops it with TimeoutError if it has not finished
howLong nanoseconds from now.
Details#
It works as Effect.timeout does under a Scheduler. If the deadline passes while the fiber
is parked inside body, such as in a PoolFiber.join or Pool.yieldNow, the pool
interrupts the fiber, and if it passes while the fiber runs, the fiber is interrupted at its
next park inside body. Each frame of body is abandoned from its park, innermost first,
which runs Drop hooks and non-parking finalizers. Then this call fails with TimeoutError.
A success or typed failure of body before the deadline is returned unchanged. Nested
timeouts work; the one whose deadline passes first stops. The pool measures time on the OS
monotonic clock, from this call.
Gotchas#
Only a pool fiber has the
PoolTaskprovider it needs.The effect stops only at a park: code between two parks always runs to its end, and an effect that never parks never stops.
ensuringfinalizers inside it do not run when it stops.Fibers forked inside it keep running; interrupt them, or wait for them.
ThreadPool#
pub struct ThreadPoolThe owner of a pool's worker threads: a work-stealing pool of native threads that runs fibers in parallel.
When to use#
Call ThreadPool.make to start the worker threads, then Pool.block on a normal thread to
run a program on the pool. In a fiber, start more fibers with Pool.fork and wait for one
with PoolFiber.join or PoolFiber.await.
Details#
Each fiber is a Transferable lazy effect, so a fiber can start on one worker, park, and
continue on a different worker. Idle workers steal work from each other and then sleep, so no
worker spins. Dropping it stops every worker, joins its thread, and cancels the fibers still
unfinished, so their waiters see Cancelled.
Gotchas#
Fiber bodies, results and failures must be
Transferableand'static.The pool uses the system allocator for its own storage, not the
Allocatorof the caller.
Implementation ThreadPool#
impl ThreadPoolAssociated function make#
pub effect fn make(workers: usize) -> ThreadPool ! OutOfMemoryError | SpawnError ? &mut AllocatorStarts a pool of workers native threads, all waiting for fibers.
Details#
Zero workers means one. If a thread fails to start, the ones already started are stopped and joined before the error returns.
Method pool#
pub fn pool(self: &Self) -> PoolReturns a handle to this pool.
Implementation Drop for ThreadPool#
impl Drop for ThreadPoolOperation drop#
fn drop(self: &mut ThreadPool) -> ()Category: Concurrency.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.