\chapter{The threads library}
\label{c:threads}\cutname{threads.html}
%HEVEA\cutname{libthreads.html}

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

The "threads" library is implemented on top of the threading
facilities provided by the operating system: POSIX 1003.1c threads for
Linux, MacOS, and other Unix-like systems; Win32 threads for Windows.
Only one thread at a time is allowed to run OCaml code, hence
opportunities for parallelism are limited to the parts of the program
that run system or C library code.  However, threads provide
concurrency and can be used to structure programs as several
communicating processes.  Threads also efficiently support concurrent,
overlapping I/O operations.

Programs that use threads must be linked as follows:
\begin{alltt}
        ocamlc -I +threads \var{other options} unix.cma threads.cma \var{other files}
        ocamlopt -I +threads \var{other options} unix.cmxa threads.cmxa \var{other files}
\end{alltt}
Compilation units that use the "threads" library must also be compiled with
the "-I +threads" option (see chapter~\ref{c:camlc}).

\begin{linklist}
\libdocitem{Thread}{lightweight threads}
\libdocitem{Mutex}{locks for mutual exclusion}
\libdocitem{Condition}{condition variables to synchronize between threads}
\libdocitem{Semaphore}{semaphores, another thread synchronization mechanism}
\libdocitem{Event}{first-class synchronous communication}
\end{linklist}
