Lwt provides lightweight (a.k.a. cooperative or green) threads for OCaml. Normally-blocking operations can be run concurrently in a single OCaml process, without managing system threads or locking. Lwt threads are type-disciplined and composable – Lwt is a monad.
Here is a simplistic program which requests the Google search page, and fails if the request is not completed in five seconds:
let () =
let request =
let%lwt addresses = Lwt_unix.getaddrinfo "google.com" "80" [] in
let server = (List.hd addresses).Lwt_unix.ai_addr in
Lwt_io.(with_connection server (fun (incoming, outgoing) ->
let%lwt () = write outgoing "GET / HTTP/1.1\r\n" in
let%lwt () = write outgoing "Connection: close\r\n\r\n" in
let%lwt response = read incoming in
Lwt.return (Some response)))
in
let timeout =
let%lwt () = Lwt_unix.sleep 5. in
Lwt.return None
in
match Lwt_main.run (Lwt.pick [request; timeout]) with
| Some response -> print_string response
| None -> prerr_endline "Request timed out"; exit 1The above program can be compiled and run with
ocamlfind opt -package lwt.unix -package lwt.ppx -linkpkg -o request example.ml
./request
opam install lwt
Documentation can be found here. There are also some examples
available in doc/examples.
Open an issue, visit Gitter chat, email the maintainer, or ask in #ocaml. If you think enough people will be interested in the answer, it is also possible to ask on Stack Overflow.
Lwt is a very mature library, but there is considerable room for improvement. Contributions are welcome. To clone the source and install a development version,
opam source --dev-repo --pin lwt
This will also install the development dependency OASIS.
A list of project suggestions and a roadmap can be found on the wiki.
Lwt is released under the LGPL, with the OpenSSL linking exception. See
COPYING.