package octez-proto-libs

  1. Overview
  2. Docs

Module Lwt: cooperative light-weight threads.

This module defines cooperative light-weight threads with their primitives. A light-weight thread represent a computation that may be not terminated, for example because it is waiting for some event to happen.

Lwt threads are cooperative in the sense that switching to another thread is always explicit (with wakeup or wakeup_exn). When a thread is running, it executes as much as possible, and then returns (a value or an error) or sleeps.

Note that inside a Lwt thread, exceptions must be raised with fail instead of raise. Also the try ... with ... construction will not catch Lwt errors. You must use catch instead. You can also use wrap for functions that may raise normal exception.

Lwt also provides the syntax extension Pa_lwt to make code using Lwt more readable.

Definitions and basics

type 'a t = 'a Lwt.t

The type of threads returning a result of type 'a.

val return : 'a -> 'a t

return e is a thread whose return value is the value of the expression e.

val bind : 'a t -> ('a -> 'b t) -> 'b t

bind t f is a thread which first waits for the thread t to terminate and then, if the thread succeeds, behaves as the application of function f to the return value of t. If the thread t fails, bind t f also fails, with the same exception.

The expression bind t (fun x -> t') can intuitively be read as let x = t in t', and if you use the lwt.syntax syntax extension, you can write a bind operation like that: lwt x = t in t'.

Note that bind is also often used just for synchronization purpose: t' will not execute before t is terminated.

The result of a thread can be bound several time.

val (>>=) : 'a t -> ('a -> 'b t) -> 'b t

t >>= f is an alternative notation for bind t f.

val (=<<) : ('a -> 'b t) -> 'a t -> 'b t

f =<< t is t >>= f

val map : ('a -> 'b) -> 'a t -> 'b t

map f m map the result of a thread. This is the same as bind m (fun x -> return (f x))

val (>|=) : 'a t -> ('a -> 'b) -> 'b t

m >|= f is map f m

val (=|<) : ('a -> 'b) -> 'a t -> 'b t

f =|< m is map f m

Pre-allocated threads

val return_unit : unit t

return_unit = return ()

val return_none : 'a option t

return_none = return None

val return_nil : 'a list t

return_nil = return []

val return_true : bool t

return_true = return true

val return_false : bool t

return_false = return false

Multi-threads composition

val join : unit t list -> unit t

join l waits for all threads in l to terminate. If one of the threads fails, then join l will fails with the same exception as the first one to terminate.

Note: join leaves the local values of the current thread unchanged.

val (<&>) : unit t -> unit t -> unit t

t <&> t' is the same as join [t; t']

OCaml

Innovation. Community. Security.