2 * Copyright (C) 2003, HELM Team.
4 * This file is part of HELM, an Hypertextual, Electronic
5 * Library of Mathematics, developed at the Computer Science
6 * Department, University of Bologna, Italy.
8 * HELM is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * HELM is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with HELM; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 * For details, see the HELM World-Wide-Web page,
24 * http://cs.unibo.it/helm/.
27 let debug_print = let debug = false in fun s -> if debug then prerr_endline s;;
32 val mutex = Mutex.create ()
34 (** condition variable: 'no readers is currently reading' *)
35 val noReaders = Condition.create ()
38 val mutable readersCount = 0
40 method private incrReadersCount = (* internal, not exported *)
41 self#doCritical (lazy (
42 readersCount <- readersCount + 1
45 method private decrReadersCount = (* internal, not exported *)
46 self#doCritical (lazy (
47 if readersCount > 0 then readersCount <- readersCount - 1;
50 method private signalNoReaders = (* internal, not exported *)
51 self#doCritical (lazy (
52 if readersCount = 0 then Condition.signal noReaders
55 method private doCritical: 'a. 'a lazy_t -> 'a =
57 debug_print "<doCritical>";
60 let res = Lazy.force action in
62 debug_print "</doCritical>";
68 method private doReader: 'a. 'a lazy_t -> 'a =
70 debug_print "<doReader>";
72 self#decrReadersCount;
75 self#incrReadersCount;
76 let res = (try Lazy.force action with e -> (cleanup (); raise e)) in
78 debug_print "</doReader>";
81 (* TODO may starve!!!! is what we want or not? *)
82 method private doWriter: 'a. 'a lazy_t -> 'a =
84 debug_print "<doWriter>";
85 self#doCritical (lazy (
86 while readersCount > 0 do
87 Condition.wait noReaders mutex
89 let res = Lazy.force action in
90 debug_print "</doWriter>";