Moonpool_forkjoin
Fork-join primitives.
NOTE These are only available on OCaml 5.0 and above.
both f g
runs f()
and g()
, potentially in parallel, and returns their result when both are done. If any of f()
and g()
fails, then the whole computation fails.
This must be run from within the pool: for example, inside Pool.run
or inside a Fut.spawn
computation. This is because it relies on an effect handler to be installed.
NOTE this is only available on OCaml 5.
Same as both f g |> ignore
.
NOTE this is only available on OCaml 5.
for_ n f
is the parallel version of for i=0 to n-1 do f i done
.
f
is called with parameters low
and high
and must use them like so:
for j = low to high do (* … actual work *) done
. If chunk_size=1
then low=high
and the loop is not actually needed.
Example:
let total_sum = Atomic.make 0
let() = for_ ~chunk_size:5 100
(fun low high ->
(* iterate on the range sequentially. The range should have 5 items or less. *)
let local_sum = ref 0 in
for j=low to high do
local_sum := !local_sum + j
done;
ignore (Atomic.fetch_and_add total_sum !local_sum : int)))
let() = assert (Atomic.get total_sum = 4950)
Note how we still compute a local sum sequentially in (fun low high -> …)
, before combining it wholesale into total_sum
. When the chunk size is large, this can have a dramatic impact on the synchronization overhead.
When chunk_size
is not provided, the library will attempt to guess a value that keeps all cores busy but runs as few tasks as possible to reduce the synchronization overhead.
Use ~chunk_size:1
if you explicitly want to run each iteration of the loop in its own task.
NOTE this is only available on OCaml 5.
all_array fs
runs all functions in fs
in tasks, and waits for all the results.
NOTE this is only available on OCaml 5.
all_list fs
runs all functions in fs
in tasks, and waits for all the results.
NOTE this is only available on OCaml 5.
all_init n f
runs functions f 0
, f 1
, … f (n-1)
in tasks, and waits for all the results.
NOTE this is only available on OCaml 5.
map_array f arr
is like Array.map f arr
, but runs in parallel.
NOTE this is only available on OCaml 5.