Goroutines in OCaml

Our example demonstrates the use of lightweight threads of execution. Here’s the source code translated into OCaml.

let f from =
  for i = 0 to 2 do
    Printf.printf "%s : %d\n" from i
  done

let () =
  (* Call the function directly *)
  f "direct";

  (* Create a new thread to run the function concurrently *)
  let _ = Thread.create f "thread" in

  (* Start a thread with an anonymous function *)
  let _ = Thread.create (fun () ->
    Printf.printf "going\n";
  ) () in

  (* Wait for a second to let threads finish execution *)
  Thread.delay 1.0;
  Printf.printf "done\n";

To run the program, compile the code and execute it.

First, save the code into a file named example.ml.

$ ocamlfind ocamlc -thread -package threads -linkpkg example.ml -o example

Then, run the compiled program:

$ ./example
direct : 0
direct : 1
direct : 2
thread : 0
going
thread : 1
thread : 2
done

In this example, the output of the main function call is shown first, followed by the output from the two concurrent threads. Output from the threads may be interleaved, reflecting the concurrent execution.