Channels in OCaml

open Lwt

let main () =
  (* Create a new channel using Lwt_mvar *)
  let messages = Lwt_mvar.create_empty () in

  (* Send a value into the channel using Lwt_mvar.put *)
  let _ = Lwt.async (fun () -> Lwt_mvar.put messages "ping") in

  (* Receive a value from the channel using Lwt_mvar.take *)
  let%lwt msg = Lwt_mvar.take messages in
  Lwt_io.printf "%s\n" msg

let () = Lwt_main.run (main ())

Channels in OCaml can be implemented using the Lwt_mvar module from the Lwt library. These channels connect concurrent threads. You can send values into channels from one thread and receive those values in another thread.

Create a new channel with Lwt_mvar.create_empty (). Channels are typed by the values they convey.

Send a value into a channel using the Lwt_mvar.put function. Here we send "ping" to the messages channel we made above, from a new async thread.

The Lwt_mvar.take function receives a value from the channel. Here we’ll receive the "ping" message we sent above and print it out.

When we run the program, the "ping" message is successfully passed from one thread to another via our channel.

$ ocaml channels.ml 
ping

By default, sends and receives block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the "ping" message without having to use any other synchronization.

Note that this OCaml implementation uses the Lwt library for concurrency, which provides a cooperative threading model. The Lwt_mvar module is used to create a synchronization primitive similar to channels in other languages.