Created
October 9, 2014 12:47
-
-
Save avsm/0fb00c14978a216b7ddb to your computer and use it in GitHub Desktop.
Example of Lwt thread-local storage values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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