ocaml-core / base / core / lib_test /

(* Test Condition.timedwait *)

  This only tests the pthread_cond_timedwait wrapper and not the underlying
  unix function. Both branches (timeout, success) are tested; all the possible
  race conditions are assumed to be handled properly by pthread and not tested.
open Core.Std
open OUnit

let run () =
  let v_mtx = Mutex.create ()
  and cnd_v_is_true = Condition.create ()
  and v = ref false in

  let v_setter () =
    Thread.delay 0.1;
    Mutex.lock v_mtx;
    v := true;
    Condition.signal cnd_v_is_true;
    Mutex.unlock v_mtx;

  let wait_for_v tmout =
    let timeout = Unix.gettimeofday () +. tmout in
    not (Condition.timedwait cnd_v_is_true v_mtx (Time.of_float timeout))

  Mutex.lock v_mtx;

  (* This condition wait is expected to timeout. *)
    let timedout = wait_for_v 0.1 in
    assert timedout

  ignore (Thread.create v_setter ():Thread.t);

  (* Now we have a thread that sets the condition so we expect to not timeout.
    let timedout = wait_for_v 0.5 in
    assert (not timedout);
    assert !v

let test = "Condition_test" >::: [
  "test" >:: (fun () ->
    "1" @? (try run (); true with e ->
              eprintf "in cond\
 ition test:%s\n%!" (Exn.to_string e);
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.