File: mutex.ml

package info (click to toggle)
ocaml 3.12.1-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 25,412 kB
  • sloc: ml: 245,686; ansic: 39,092; sh: 5,924; asm: 5,371; lisp: 4,963; makefile: 3,150; perl: 82; fortran: 21; sed: 19; cs: 9; tcl: 2
file content (38 lines) | stat: -rw-r--r-- 1,760 bytes parent folder | download
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
(***********************************************************************)
(*                                                                     *)
(*                           Objective Caml                            *)
(*                                                                     *)
(*         Xavier Leroy and Damien Doligez, INRIA Rocquencourt         *)
(*                                                                     *)
(*  Copyright 1996 Institut National de Recherche en Informatique et   *)
(*  en Automatique.  All rights reserved.  This file is distributed    *)
(*  under the terms of the GNU Library General Public License, with    *)
(*  the special exception on linking described in file ../../LICENSE.  *)
(*                                                                     *)
(***********************************************************************)

(* $Id: mutex.ml 9547 2010-01-22 12:48:24Z doligez $ *)

type t = { mutable locked: bool; mutable waiting: Thread.t list }

let create () = { locked = false; waiting = [] }

let rec lock m =
  if m.locked then begin                (* test and set atomic *)
    Thread.critical_section := true;
    m.waiting <- Thread.self() :: m.waiting;
    Thread.sleep();
    lock m
  end else begin
    m.locked <- true                    (* test and set atomic *)
  end

let try_lock m =                        (* test and set atomic *)
  if m.locked then false else begin m.locked <- true; true end

let unlock m =
  (* Don't play with Thread.critical_section here because of Condition.wait *)
  let w = m.waiting in                  (* atomic *)
  m.waiting <- [];                      (* atomic *)
  m.locked <- false;                    (* atomic *)
  List.iter Thread.wakeup w