]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/ocaml/contrib/otherlibs/threads/mutex.ml
Inital import
[l4.git] / l4 / pkg / ocaml / contrib / otherlibs / threads / mutex.ml
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 (***********************************************************************)
13
14 (* $Id: mutex.ml 4144 2001-12-07 13:41:02Z xleroy $ *)
15
16 type t = { mutable locked: bool; mutable waiting: Thread.t list }
17
18 let create () = { locked = false; waiting = [] }
19
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
29
30 let try_lock m =                        (* test and set atomic *)
31   if m.locked then false else begin m.locked <- true; true end
32
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
39