src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Wed Aug 15 22:21:13 2007 +0200 (2007-08-15 ago)
changeset 24291 fa72aab966dc
parent 24214 0482ecc4ef11
child 24297 a50cdc42798d
permissions -rw-r--r--
main: wait_timeout (1 second);
wenzelm@23961
     1
(*  Title:      Pure/ML-Systems/multithreading_polyml.ML
wenzelm@23961
     2
    ID:         $Id$
wenzelm@23961
     3
    Author:     Makarius
wenzelm@23961
     4
wenzelm@24214
     5
Multithreading in Poly/ML 5.1 or later (cf. polyml/basis/Thread.sml).
wenzelm@23961
     6
*)
wenzelm@23961
     7
wenzelm@23961
     8
open Thread;
wenzelm@23961
     9
wenzelm@24208
    10
signature MULTITHREADING =
wenzelm@24208
    11
sig
wenzelm@24208
    12
  include MULTITHREADING
wenzelm@24214
    13
  val uninterruptible: (Thread.threadAttribute list -> 'a -> 'b) -> 'a -> 'b
wenzelm@24214
    14
  val interruptible: (Thread.threadAttribute list -> 'a -> 'b) -> 'a -> 'b
wenzelm@24208
    15
end;
wenzelm@24208
    16
wenzelm@23961
    17
structure Multithreading: MULTITHREADING =
wenzelm@23961
    18
struct
wenzelm@23961
    19
wenzelm@24072
    20
(* options *)
wenzelm@24069
    21
wenzelm@24119
    22
val trace = ref 0;
wenzelm@24119
    23
fun tracing level msg =
wenzelm@24119
    24
  if level <= ! trace
wenzelm@23981
    25
  then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
wenzelm@23981
    26
  else ();
wenzelm@23961
    27
wenzelm@23981
    28
val available = true;
wenzelm@23973
    29
val max_threads = ref 1;
wenzelm@23973
    30
wenzelm@23973
    31
wenzelm@24069
    32
(* misc utils *)
wenzelm@24069
    33
wenzelm@24208
    34
fun cons x xs = x :: xs;
wenzelm@24069
    35
wenzelm@24208
    36
fun change r f = r := f (! r);
wenzelm@24069
    37
wenzelm@24069
    38
fun inc i = (i := ! i + 1; ! i);
wenzelm@24069
    39
fun dec i = (i := ! i - 1; ! i);
wenzelm@24069
    40
wenzelm@24208
    41
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    42
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    43
wenzelm@24208
    44
wenzelm@24208
    45
(* thread attributes *)
wenzelm@24208
    46
wenzelm@24208
    47
fun with_attributes new_atts f x =
wenzelm@24208
    48
  let
wenzelm@24208
    49
    val orig_atts = Thread.getAttributes ();
wenzelm@24208
    50
    fun restore () = Thread.setAttributes orig_atts;
wenzelm@24208
    51
  in
wenzelm@24208
    52
    Exn.release
wenzelm@24214
    53
    (*RACE for fully asynchronous interrupts!*)
wenzelm@24214
    54
    (let
wenzelm@24208
    55
        val _ = Thread.setAttributes new_atts;
wenzelm@24214
    56
        val result = Exn.capture (f orig_atts) x;
wenzelm@24208
    57
        val _ = restore ();
wenzelm@24208
    58
      in result end
wenzelm@24208
    59
      handle Interrupt => (restore (); Exn.Exn Interrupt))
wenzelm@24208
    60
  end;
wenzelm@24208
    61
wenzelm@24208
    62
fun with_interrupt_state state = with_attributes [Thread.InterruptState state];
wenzelm@24208
    63
wenzelm@24208
    64
fun uninterruptible f x = with_interrupt_state Thread.InterruptDefer f x;
wenzelm@24208
    65
fun interruptible f x = with_interrupt_state Thread.InterruptAsynchOnce f x;
wenzelm@24208
    66
wenzelm@24069
    67
wenzelm@23961
    68
(* critical section -- may be nested within the same thread *)
wenzelm@23961
    69
wenzelm@23961
    70
local
wenzelm@23961
    71
wenzelm@24063
    72
val critical_lock = Mutex.mutex ();
wenzelm@24063
    73
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
    74
val critical_name = ref "";
wenzelm@24063
    75
wenzelm@23961
    76
in
wenzelm@23961
    77
wenzelm@23961
    78
fun self_critical () =
wenzelm@23961
    79
  (case ! critical_thread of
wenzelm@23961
    80
    NONE => false
wenzelm@23961
    81
  | SOME id => Thread.equal (id, Thread.self ()));
wenzelm@23961
    82
wenzelm@23991
    83
fun NAMED_CRITICAL name e =
wenzelm@23961
    84
  if self_critical () then e ()
wenzelm@23961
    85
  else
wenzelm@24214
    86
    uninterruptible (fn atts => fn () =>
wenzelm@24208
    87
      let
wenzelm@24208
    88
        val name' = ! critical_name;
wenzelm@24208
    89
        val _ =
wenzelm@24208
    90
          if Mutex.trylock critical_lock then ()
wenzelm@24208
    91
          else
wenzelm@24208
    92
            let
wenzelm@24208
    93
              val timer = Timer.startRealTimer ();
wenzelm@24208
    94
              val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24208
    95
              val _ = Mutex.lock critical_lock;
wenzelm@24208
    96
              val time = Timer.checkRealTimer timer;
wenzelm@24208
    97
              val _ = tracing (if Time.> (time, Time.fromMilliseconds 10) then 3 else 4) (fn () =>
wenzelm@24208
    98
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
    99
            in () end;
wenzelm@24208
   100
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   101
        val _ = critical_name := name;
wenzelm@24214
   102
        val result = Exn.capture (with_attributes atts (fn _ => e)) ();
wenzelm@24208
   103
        val _ = critical_name := "";
wenzelm@24208
   104
        val _ = critical_thread := NONE;
wenzelm@24208
   105
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   106
      in Exn.release result end) ();
wenzelm@23961
   107
wenzelm@23991
   108
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   109
wenzelm@23961
   110
end;
wenzelm@23961
   111
wenzelm@23973
   112
wenzelm@24208
   113
(* scheduling -- multiple threads working on a queue of tasks *)
wenzelm@24208
   114
wenzelm@24208
   115
datatype 'a task =
wenzelm@24208
   116
  Task of {body: unit -> unit, cont: 'a -> 'a, fail: 'a -> 'a} | Wait | Terminate;
wenzelm@23973
   117
wenzelm@24069
   118
local
wenzelm@24069
   119
wenzelm@24069
   120
val protected_name = ref "";
wenzelm@24069
   121
wenzelm@24069
   122
in
wenzelm@24063
   123
wenzelm@24214
   124
fun schedule n next_task = uninterruptible (fn _ => fn tasks =>
wenzelm@23973
   125
  let
wenzelm@23973
   126
    (*protected execution*)
wenzelm@23973
   127
    val lock = Mutex.mutex ();
wenzelm@24063
   128
    fun PROTECTED name e =
wenzelm@23973
   129
      let
wenzelm@24144
   130
        val name' = ! protected_name;
wenzelm@23981
   131
        val _ =
wenzelm@23981
   132
          if Mutex.trylock lock then ()
wenzelm@23981
   133
          else
wenzelm@24144
   134
            let
wenzelm@24144
   135
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24144
   136
              val _ = Mutex.lock lock;
wenzelm@24144
   137
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": passed");
wenzelm@24144
   138
            in () end;
wenzelm@24069
   139
        val _ = protected_name := name;
wenzelm@23973
   140
        val res = Exn.capture e ();
wenzelm@24069
   141
        val _ = protected_name := "";
wenzelm@23973
   142
        val _ = Mutex.unlock lock;
wenzelm@23973
   143
      in Exn.release res end;
wenzelm@23973
   144
wenzelm@24072
   145
    (*wakeup condition*)
wenzelm@24072
   146
    val wakeup = ConditionVar.conditionVar ();
wenzelm@24072
   147
    fun wakeup_all () = ConditionVar.broadcast wakeup;
wenzelm@24072
   148
    fun wait () = ConditionVar.wait (wakeup, lock);
wenzelm@24291
   149
    fun wait_timeout () = ConditionVar.waitUntil (wakeup, lock, Time.now () + Time.fromSeconds 1);
wenzelm@24072
   150
wenzelm@24214
   151
    (*queue of tasks*)
wenzelm@23973
   152
    val queue = ref tasks;
wenzelm@24072
   153
    val active = ref 0;
wenzelm@24119
   154
    fun trace_active () = tracing 1 (fn () => "SCHEDULE: " ^ Int.toString (! active) ^ " active");
wenzelm@24072
   155
    fun dequeue () =
wenzelm@23973
   156
      let
wenzelm@23981
   157
        val (next, tasks') = next_task (! queue);
wenzelm@23973
   158
        val _ = queue := tasks';
wenzelm@24072
   159
      in
wenzelm@24208
   160
        (case next of Wait =>
wenzelm@24208
   161
          (dec active; trace_active ();
wenzelm@24208
   162
            wait ();
wenzelm@24208
   163
            inc active; trace_active ();
wenzelm@24208
   164
            dequeue ())
wenzelm@24208
   165
        | _ => next)
wenzelm@24072
   166
      end;
wenzelm@23973
   167
wenzelm@24208
   168
    (*pool of running threads*)
wenzelm@23973
   169
    val status = ref ([]: exn list);
wenzelm@24208
   170
    val running = ref ([]: Thread.thread list);
wenzelm@24208
   171
    fun start f =
wenzelm@24208
   172
      (inc active;
wenzelm@24208
   173
       change running (cons (Thread.fork (f, [Thread.InterruptState Thread.InterruptDefer]))));
wenzelm@24208
   174
    fun stop () =
wenzelm@24208
   175
      (dec active;
wenzelm@24208
   176
       change running (List.filter (fn t => not (Thread.equal (t, Thread.self ())))));
wenzelm@24208
   177
wenzelm@24208
   178
   (*worker thread*)
wenzelm@24208
   179
    fun worker () =
wenzelm@24072
   180
      (case PROTECTED "dequeue" dequeue of
wenzelm@24208
   181
        Task {body, cont, fail} =>
wenzelm@24214
   182
          (case Exn.capture (interruptible (fn _ => body)) () of
wenzelm@24208
   183
            Exn.Result () =>
wenzelm@24208
   184
              (PROTECTED "cont" (fn () => (change queue cont; wakeup_all ())); worker ())
wenzelm@23981
   185
          | Exn.Exn exn =>
wenzelm@24208
   186
              PROTECTED "fail" (fn () =>
wenzelm@24208
   187
                (change status (cons exn); change queue fail; stop (); wakeup_all ())))
wenzelm@24208
   188
      | Terminate => PROTECTED "terminate" (fn () => (stop (); wakeup_all ())));
wenzelm@23973
   189
wenzelm@23973
   190
    (*main control: fork and wait*)
wenzelm@23973
   191
    fun fork 0 = ()
wenzelm@24208
   192
      | fork k = (start worker; fork (k - 1));
wenzelm@24063
   193
    val _ = PROTECTED "main" (fn () =>
wenzelm@24063
   194
     (fork (Int.max (n, 1));
wenzelm@24208
   195
      while not (List.null (! running)) do
wenzelm@24208
   196
      (trace_active ();
wenzelm@24208
   197
       if not (List.null (! status)) then (List.app Thread.interrupt (! running)) else ();
wenzelm@24291
   198
       wait_timeout ())));
wenzelm@23973
   199
wenzelm@24208
   200
  in ! status end);
wenzelm@23973
   201
wenzelm@23961
   202
end;
wenzelm@23961
   203
wenzelm@24069
   204
end;
wenzelm@24069
   205
wenzelm@23991
   206
val NAMED_CRITICAL = Multithreading.NAMED_CRITICAL;
wenzelm@23961
   207
val CRITICAL = Multithreading.CRITICAL;
wenzelm@24208
   208