Skip to content

Instantly share code, notes, and snippets.

@avsm
Created October 9, 2014 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avsm/0fb00c14978a216b7ddb to your computer and use it in GitHub Desktop.
Save avsm/0fb00c14978a216b7ddb to your computer and use it in GitHub Desktop.
Example of Lwt thread-local storage values
(* Build with:
ocamlbuild -use-ocamlfind -pkg lwt.unix -tag annot test.native
*)
let id_key = Lwt.new_key ()
let log fmt =
let tid =
match Lwt.get id_key with
| None -> "<unknown>"
| Some id -> id
in
Printf.(kprintf (fun (msg:string) -> printf "[%s] %s\n%!" tid msg) fmt)
let in_thread ?id fn =
Lwt.with_value id_key id fn
let () = Lwt_unix.run (
let open Lwt in
log "main function starts";
in_thread ~id:"thread 1" (fun () -> log "hello");
in_thread ~id:"thread 1" (fun () -> log "world");
let rec looper n () =
match n with
| 0 -> return_unit
| n ->
log "looper %d" n;
Lwt_unix.sleep (Random.float 1.0)
>>= looper (n-1)
in
join [
in_thread ~id:"foo" (looper 10);
in_thread ~id:"bar" (looper 5);
looper 7 ()
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment