3 * Stefano Zacchiroli <zack@cs.unibo.it>
4 * for the HELM Team http://helm.cs.unibo.it/
6 * This file is part of HELM, an Hypertextual, Electronic
7 * Library of Mathematics, developed at the Computer Science
8 * Department, University of Bologna, Italy.
10 * HELM is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * HELM is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with HELM; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * For details, see the HELM World-Wide-Web page,
26 * http://helm.cs.unibo.it/
29 let debug_print = let debug = false in fun s -> if debug then prerr_endline s;;
34 val mutex = Mutex.create ()
36 (** condition variable: 'no readers is currently reading' *)
37 val noReaders = Condition.create ()
40 val mutable readersCount = 0
42 method private incrReadersCount = (* internal, not exported *)
43 self#doCritical (lazy (
44 readersCount <- readersCount + 1
47 method private decrReadersCount = (* internal, not exported *)
48 self#doCritical (lazy (
49 if readersCount > 0 then readersCount <- readersCount - 1;
52 method private signalNoReaders = (* internal, not exported *)
53 self#doCritical (lazy (
54 if readersCount = 0 then Condition.signal noReaders
57 method private doCritical: 'a. 'a lazy_t -> 'a =
59 debug_print "<doCritical>";
62 let res = Lazy.force action in
64 debug_print "</doCritical>";
70 method private doReader: 'a. 'a lazy_t -> 'a =
72 debug_print "<doReader>";
74 self#decrReadersCount;
77 self#incrReadersCount;
78 let res = (try Lazy.force action with e -> (cleanup (); raise e)) in
80 debug_print "</doReader>";
83 (* TODO may starve!!!! is what we want or not? *)
84 method private doWriter: 'a. 'a lazy_t -> 'a =
86 debug_print "<doWriter>";
87 self#doCritical (lazy (
88 while readersCount > 0 do
89 Condition.wait noReaders mutex
91 let res = Lazy.force action in
92 debug_print "</doWriter>";