File: sample.ml

package info (click to toggle)
ocamlnet 4.1.9-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 54,024 kB
  • sloc: ml: 151,939; ansic: 11,071; sh: 2,003; makefile: 1,310
file content (50 lines) | stat: -rw-r--r-- 1,574 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(* From Patrick M Doane *)

(* This example demonstrates an important property of Unixqueue:
   the queues are thread-safe. Even better, one can add event from
   one thread into a running Unixqueue that is being executed by 
   a different thread. This "event injection" will interrupt the
   queue if it is waiting, and makes it consider the additional event.
 *)

let esys = Unixqueue.create_unix_event_system()
let after timeout f =
  let group = Unixqueue.new_group esys in
  Unixqueue.once esys group timeout f
;;

let m = Mutex.create();;
let c = Condition.create();;
  (* Unixqueue.run should not be called before any event handlers are
   * registered; it would return immediately. The condition variable
   * is used to wait until the first handler is added to the queue.
   *)

let queue_it () =
  print_endline "queue_it started"; flush stdout;
  after 4.0 (fun () -> print_endline "4 seconds"; flush stdout);
  Mutex.lock m;
  Condition.signal c;
  Mutex.unlock m;
  Thread.delay 1.0;
  print_endline "1 second"; flush stdout;
  (* The following is an event injection from a different thread: *)
  after 1.0 (fun () -> print_endline "2 seconds"; flush stdout);  
  print_endline "queue_it finishes"; flush stdout;
;;

let run_it () =
  print_endline "run_it started"; flush stdout;
  Condition.wait c m;
  print_endline "run_it executes event system"; flush stdout;
  Unixqueue.run esys;
  print_endline "run_it finishes"; flush stdout;
;;

Mutex.lock m;;
let t1 = Thread.create queue_it ();;
let t2 = Thread.create run_it ();;

Thread.join t1;
Thread.join t2