OCaml Domains and Parallelism
Before OCaml 5, a program could run on only one CPU core at a time. OCaml 5 introduced domains: units of parallelism that run truly in parallel on different cores, sharing the same heap. This lesson explains the concepts and shows deterministic examples: the printed results do not depend on how the operating system schedules the domains.
Concurrency versus parallelism
| Term | Meaning | OCaml 5 tool |
|---|---|---|
| Concurrency | many tasks in progress, interleaved (e.g. waiting for the network) | effect handlers, libraries like Eio and Lwt |
| Parallelism | computations really running at the same time on several cores | Domain, Domainslib |
Domains are heavyweight: each one is an OS thread with its own minor heap. Create roughly one per core (Domain.recommended_domain_count ()), not one per task.
Spawning and joining
Domain.spawn f starts running f () in a new domain and returns a handle. Domain.join d waits for it to finish and returns its result:
let sum_range lo hi =
let total = ref 0 in
for i = lo to hi do
total := !total + i
done;
!total
let () =
let left = Domain.spawn (fun () -> sum_range 1 5_000_000) in
let right = Domain.spawn (fun () -> sum_range 5_000_001 10_000_000) in
let a = Domain.join left and b = Domain.join right in
Printf.printf "left %d + right %d = %d\n" a b (a + b);
Printf.printf "check: %d\n" (sum_range 1 10_000_000)left 12500002500000 + right 37500002500000 = 50000005000000
check: 50000005000000
Each domain works on its own data and returns a value; the main domain combines the results. This "split, compute, join" pattern is deterministic because the domains share nothing mutable.
Note: We print only in the main domain, after joining. If several domains print at the same time, the lines can appear in any order.
Shared state needs Atomic or Mutex
When domains update the same variable, a plain ref is a data race: increments can be lost. Use Atomic for single values:
let () =
let hits = Atomic.make 0 in
let worker () =
for _ = 1 to 100_000 do
Atomic.incr hits
done
in
let domains = List.init 4 (fun _ -> Domain.spawn worker) in
List.iter Domain.join domains;
Printf.printf "hits = %d\n" (Atomic.get hits)hits = 400000
Atomic.incr, Atomic.fetch_and_add and Atomic.compare_and_set are indivisible operations, so the total is always exactly 400000. With a plain ref and incr, the result could be anything up to 400000.
For larger critical sections, protect data with a Mutex:
let () =
let lock = Mutex.create () in
let log = ref [] in
let record id =
for step = 1 to 3 do
Mutex.protect lock (fun () -> log := (id, step) :: !log)
done
in
let ds = List.init 3 (fun id -> Domain.spawn (fun () -> record id)) in
List.iter Domain.join ds;
(* the interleaving varies from run to run, so sort before printing *)
let entries = List.sort compare !log in
Printf.printf "%d entries\n" (List.length entries);
List.iter (fun (id, s) -> Printf.printf "(%d,%d) " id s) entries;
print_newline ()9 entries
(0,1) (0,2) (0,3) (1,1) (1,2) (1,3) (2,1) (2,2) (2,3)
Mutex.protect m f locks m, runs f and unlocks, even if f raises.
A parallel map
A small helper that splits an array into chunks, one domain per chunk:
let parallel_map ~chunks f arr =
let n = Array.length arr in
let result = Array.make n (f arr.(0)) in
let size = (n + chunks - 1) / chunks in
let work c () =
for i = c * size to min n ((c + 1) * size) - 1 do
result.(i) <- f arr.(i) (* each domain writes its own slice: no race *)
done
in
List.init chunks (fun c -> Domain.spawn (work c)) |> List.iter Domain.join;
result
let rec collatz_len n = if n = 1 then 1 else 1 + collatz_len (if n mod 2 = 0 then n / 2 else (3 * n) + 1)
let () =
let inputs = Array.init 100_000 (fun i -> i + 1) in
let lengths = parallel_map ~chunks:4 collatz_len inputs in
let best = ref 0 in
Array.iteri (fun i l -> if l > lengths.(!best) then best := i) lengths;
Printf.printf "longest chain below 100001 starts at %d (length %d)\n" inputs.(!best) lengths.(!best)longest chain below 100001 starts at 77031 (length 351)
Writing to different indices of the same array from different domains is safe; the domains never touch the same element.
Rules of thumb
- Prefer sharing nothing: give each domain its input and combine the returned values.
- Use
Atomicfor counters and flags,Mutex(withConditionfor waiting) for compound updates. - Standard mutable structures such as
Hashtbl,QueueandBufferare not thread-safe. - Spawn about as many domains as cores. For many small tasks, use a pool such as
Domainslib.Task(an opam package). - Parallel speed-ups need enough work per domain; for tiny computations, spawning costs more than it saves.
Test yourself
What does Domain.join d return?
- unit always
- The result of the function the domain ran
- The domain id
- A mutex
Several domains increment a shared counter. What should the counter be?
int refint Atomic.tint array- A global
let
Why sort the log entries before printing in the Mutex example?
- Mutexes reverse lists
- The order in which domains run varies between runs
- Printing requires sorted data
- To remove duplicates