Chapter 28 The threads library

Warning: the threads library is deprecated since version4.08.0 of OCaml. Please switch to system threads, which have the sameAPI. Lightweight threads with VM-level scheduling are provided bythird-party libraries such as Lwt, but with a different API.

The threads library allows concurrent programming in OCaml.It provides multiple threads of control (also called lightweightprocesses) that execute concurrently in the same memory space. Threadscommunicate by in-place modification of shared data structures, or bysending and receiving data on communication channels.

The threads library is implemented by time-sharing on a singleprocessor. It will not take advantage of multi-processor machines.Using this library will therefore never make programs runfaster. However, many programs are easier to write when structured asseveral communicating processes.

Two implementations of the threads library are available, dependingon the capabilities of the operating system:

  • System threads. This implementation builds on the OS-provided threadsfacilities: POSIX 1003.1c threads for Unix, and Win32 threads forWindows. When available, system threads support both bytecode andnative-code programs.
  • VM-level threads. This implementation performs time-sharing andcontext switching at the level of the OCaml virtual machine (bytecodeinterpreter). It is available on Unix systems, and supports onlybytecode programs. It cannot be used with native-code programs.Programs that use system threads must be linked as follows:
  1. ocamlc -I +threads other options unix.cma threads.cma other files
  2. ocamlopt -I +threads other options unix.cmxa threads.cmxa other files

Compilation units that use the threads library must also be compiled withthe -I +threads option (see chapter 9).

Programs that use VM-level threads must be compiled with the -vmthreadoption to ocamlc (see chapter 9), and be linked as follows:

  1. ocamlc -vmthread other options threads.cma other files

Compilation units that use threads library must also be compiled withthe -vmthread option (see chapter 9).