src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Tue Jul 24 19:44:32 2007 +0200 (2007-07-24 ago)
changeset 23961 9e7e1e309ebd
child 23973 b6ce6de5b700
permissions -rw-r--r--
Multithreading in Poly/ML (version 5.1).
wenzelm@23961
     1
(*  Title:      Pure/ML-Systems/multithreading_polyml.ML
wenzelm@23961
     2
    ID:         $Id$
wenzelm@23961
     3
    Author:     Makarius
wenzelm@23961
     4
wenzelm@23961
     5
Multithreading in Poly/ML (version 5.1).
wenzelm@23961
     6
*)
wenzelm@23961
     7
wenzelm@23961
     8
open Thread;
wenzelm@23961
     9
wenzelm@23961
    10
structure Multithreading: MULTITHREADING =
wenzelm@23961
    11
struct
wenzelm@23961
    12
wenzelm@23961
    13
val number_of_threads = ref 0;
wenzelm@23961
    14
wenzelm@23961
    15
wenzelm@23961
    16
(* FIXME tmp *)
wenzelm@23961
    17
fun message s =
wenzelm@23961
    18
  (TextIO.output (TextIO.stdErr, (">>> " ^ s ^ "\n")); TextIO.flushOut TextIO.stdErr);
wenzelm@23961
    19
wenzelm@23961
    20
wenzelm@23961
    21
(* critical section -- may be nested within the same thread *)
wenzelm@23961
    22
wenzelm@23961
    23
local
wenzelm@23961
    24
wenzelm@23961
    25
val critical_lock = Mutex.mutex ();
wenzelm@23961
    26
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@23961
    27
wenzelm@23961
    28
in
wenzelm@23961
    29
wenzelm@23961
    30
fun self_critical () =
wenzelm@23961
    31
  (case ! critical_thread of
wenzelm@23961
    32
    NONE => false
wenzelm@23961
    33
  | SOME id => Thread.equal (id, Thread.self ()));
wenzelm@23961
    34
wenzelm@23961
    35
fun CRITICAL e =
wenzelm@23961
    36
  if self_critical () then e ()
wenzelm@23961
    37
  else
wenzelm@23961
    38
    let
wenzelm@23961
    39
      val _ =
wenzelm@23961
    40
        if Mutex.trylock critical_lock then ()
wenzelm@23961
    41
        else
wenzelm@23961
    42
          (message "Waiting for critical lock";
wenzelm@23961
    43
           Mutex.lock critical_lock;
wenzelm@23961
    44
           message "Obtained critical lock");
wenzelm@23961
    45
      val _ = critical_thread := SOME (Thread.self ());
wenzelm@23961
    46
      val result = Exn.capture e ();
wenzelm@23961
    47
      val _ = critical_thread := NONE;
wenzelm@23961
    48
      val _ = Mutex.unlock critical_lock;
wenzelm@23961
    49
    in Exn.release result end;
wenzelm@23961
    50
wenzelm@23961
    51
end;
wenzelm@23961
    52
wenzelm@23961
    53
end;
wenzelm@23961
    54
wenzelm@23961
    55
val CRITICAL = Multithreading.CRITICAL;