Run parallel OCaml 5 code with domains and atomics

8 steps · about 2 h 6 min · Intermediate

  1. Read the parallel programming chapter (reference, OCaml manual, 25 min)

    Covers spawning domains, joining them and shared-memory safety.

  2. Spawn and join domains (reference, OCaml manual, 10 min)

    The core API for running code on another core.

  3. Share counters and flags with Atomic (reference, OCaml manual, 10 min)

    Lock-free updates such as fetch_and_add and compare_and_set.

  4. Protect larger shared structures with Mutex (reference, OCaml manual, 8 min)

    Use protect so locks are released even on exceptions.

  5. Wait for work with condition variables (reference, OCaml manual, 8 min)

    Lets a domain sleep until another signals that data is ready.

  6. Understand the OCaml memory model and data races (reference, OCaml manual, 20 min)

    Explains what is guaranteed when domains race on plain fields.

  7. Follow the multicore OCaml tutorial (repo, OCaml Multicore (GitHub), 30 min)

    Worked examples with task pools, parallel_for and channels.

  8. Use domainslib task pools for parallel_for (repo, OCaml Multicore (GitHub), 15 min)

    Avoids spawning one domain per task.