package octez-proto-libs
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
.
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.
map f m
map the result of a thread. This is the same as bind
m (fun x -> return (f x))
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
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.