Skip to content

Instantly share code, notes, and snippets.

@gaborigloi
Created August 2, 2017 08:28
Show Gist options
  • Save gaborigloi/cf5d45a19df797a47e5bbba19020035d to your computer and use it in GitHub Desktop.
Save gaborigloi/cf5d45a19df797a47e5bbba19020035d to your computer and use it in GitHub Desktop.
OCaml demo showing that a timeout mechanism using Lwt cannot interrupt Unix.sleep
(* run with "ocaml lwt_timeout_test.ml" *)
#use "topfind";;
#require "unix";;
#require "lwt";;
#require "lwt.unix";;
open Lwt;;
let f = ref "";;
Lwt.pick [(Lwt_unix.sleep 4.0 >>= fun () -> f:= "slept 4 seconds"; return_unit); (Lwt_unix.sleep 2.0 >>= fun () -> f := "slept 2 seconds"; return_unit)] |> Lwt_main.run;;
let tm = Unix.localtime (Unix.time ()) in
Printf.printf "%d:%d:%d - %s\n%!" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec !f;;
let f = ref "";;
Lwt.pick [(Lwt.wrap (fun () -> Unix.sleep 4) >>= fun () -> f:= "slept 4 seconds"; return_unit); (Lwt_unix.sleep 2.0 >>= fun () -> f := "slept 2 seconds"; return_unit)] |> Lwt_main.run;;
let tm = Unix.localtime (Unix.time ()) in
Printf.printf "%d:%d:%d - %s\n%!" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec !f;;
@gaborigloi
Copy link
Author

Output:

> ocaml lwt_timeout_test.ml
9:26:19 - slept 2 seconds
9:26:23 - slept 4 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment