Sys.Signals module for a Variant type of signals (and a set_signal function that...
[ocaml.git] / otherlibs / threads / mutex.ml
blob2858a2414de53a83edd522fc06864d362168524a
1 (***********************************************************************)
2 (* *)
3 (* Objective Caml *)
4 (* *)
5 (* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
6 (* *)
7 (* Copyright 1996 Institut National de Recherche en Informatique et *)
8 (* en Automatique. All rights reserved. This file is distributed *)
9 (* under the terms of the GNU Library General Public License, with *)
10 (* the special exception on linking described in file ../../LICENSE. *)
11 (* *)
12 (***********************************************************************)
14 (* $Id$ *)
16 type t = { mutable locked: bool; mutable waiting: Thread.t list }
18 let create () = { locked = false; waiting = [] }
20 let rec lock m =
21 if m.locked then begin (* test and set atomic *)
22 Thread.critical_section := true;
23 m.waiting <- Thread.self() :: m.waiting;
24 Thread.sleep();
25 lock m
26 end else begin
27 m.locked <- true (* test and set atomic *)
28 end
30 let try_lock m = (* test and set atomic *)
31 if m.locked then false else begin m.locked <- true; true end
33 let unlock m =
34 (* Don't play with Thread.critical_section here because of Condition.wait *)
35 let w = m.waiting in (* atomic *)
36 m.waiting <- []; (* atomic *)
37 m.locked <- false; (* atomic *)
38 List.iter Thread.wakeup w