Module Picos_std_structured.Bundle

An explicit dynamic bundle of fibers guaranteed to be joined at the end.

Bundles allow you to conveniently structure or delimit concurrency into nested scopes. After a bundle returns or raises an exception, no fibers forked to the bundle remain.

An unhandled exception, or error, within any fiber of the bundle causes all of the fibers forked to the bundle to be canceled and the bundle to raise the error exception or error exceptions raised by all of the fibers forked into the bundle.

type t

Represents a bundle of fibers.

val join_after : ?callstack:int -> ?on_return:[ `Terminate | `Wait ] -> (t -> 'a) -> 'a

join_after scope calls scope with a bundle. A call of join_after returns or raises only after scope has returned or raised and all forked fibers have terminated. If scope raises an exception, error will be called.

The optional on_return argument specifies what to do when the scope returns normally. It defaults to `Wait, which means to just wait for all the fibers to terminate on their own. When explicitly specified as ~on_return:`Terminate, then terminate ?callstack will be called on return. This can be convenient, for example, when dealing with daemon fibers.

val terminate : ?callstack:int -> t -> unit

terminate bundle cancels all of the forked fibers using the Terminate exception. After terminate has been called, no new fibers can be forked to the bundle.

The optional callstack argument specifies the number of callstack entries to capture with the Terminate exception. The default is 0.

ℹī¸ Calling terminate at the end of a bundle can be a convenient way to cancel any background fibers started by the bundle.

ℹī¸ Calling terminate does not raise the Terminate exception, but blocking operations after terminate will raise the exception to propagate cancelation unless propagation of cancelation is forbidden.

val terminate_after : ?callstack:int -> t -> seconds:float -> unit

terminate_after ~seconds bundle arranges to terminate the bundle after the specified timeout in seconds.

val error : ?callstack:int -> t -> exn -> Stdlib.Printexc.raw_backtrace -> unit

error bundle exn bt first calls terminate and then adds the exception with backtrace to the list of exceptions to be raised, unless the exception is the Terminate exception, which is not considered to signal an error by itself.

The optional callstack argument is passed to terminate.

val fork_as_promise : t -> (unit -> 'a) -> 'a Promise.t

fork_as_promise bundle thunk spawns a new fiber to the bundle that will run the given thunk. The result of the thunk will be written to the promise. If the thunk raises an exception, error will be called with that exception.

val fork : t -> (unit -> unit) -> unit

fork bundle action is equivalent to fork_as_promise bundle action |> ignore.