Module Stdlib.Domain

type t(!'a);

A domain of type 'a t runs independently, eventually producing a result of type 'a, or an exception

let spawn: (unit => 'a) => t('a);

spawn f creates a new domain that runs in parallel with the current domain.

  • raises Failure

    if the program has insufficient resources to create another domain.

let join: t('a) => Js.Promise.t('a);

join d blocks until domain d runs to completion. If d results in a value, then that is returned by join d. If d raises an uncaught exception, then that is re-raised by join d.

type id = pri int;

Domains have unique integer identifiers

let get_id: t('a) => id;

get_id d returns the identifier of the domain d

let self: unit => id;

self () is the identifier of the currently running domain

let before_first_spawn: (unit => unit) => unit;

before_first_spawn f registers f to be called before the first domain is spawned by the program. The functions registered with before_first_spawn are called on the main (initial) domain. The functions registered with before_first_spawn are called in 'first in, first out' order: the oldest function added with before_first_spawn is called first.

let at_exit: (unit => unit) => unit;

at_exit f registers f to be called when the current domain exits. Note that at_exit callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with at_exit is called first.

The at_exit function can be used in combination with at_each_spawn to clean up domain-local resources. Consider the following example:

let temp_file_key = Domain.DLS.new_key (fun _ ->
  snd (Filename.open_temp_file "" ""))

let _ = Domain.(at_each_spawn (fun _ ->
  at_exit (fun _ -> close_out (DLS.get temp_file_key))))

The snippet above uses domain-local state (Domain.DLS) to create a temporary file for each domain. The at_each_spawn callback installs an at_exit callback on each domain which closes the temporary file when the domain terminates.

let cpu_relax: unit => unit;

If busy-waiting, calling cpu_relax () between iterations will improve performance on some CPU architectures

let is_main_domain: unit => bool;

is_main_domain () returns true if called from the initial domain.

The recommended maximum number of domains which should be running simultaneously (including domains already running).

The value returned is at least 1.

module DLS: { ... };

Domain-local Storage