src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Thu Aug 16 18:53:22 2007 +0200 (2007-08-16 ago)
changeset 24297 a50cdc42798d
parent 24291 fa72aab966dc
child 24668 4058b7b0925c
permissions -rw-r--r--
improved treatment of global interrupts: Thread.EnableBroadcastInterrupt, redefine ignore/raise_interrupt;
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@24297
    62
fun uninterruptible f x = with_attributes
wenzelm@24297
    63
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer] f x;
wenzelm@24208
    64
wenzelm@24297
    65
fun interruptible f x = with_attributes
wenzelm@24297
    66
  [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce] f x;
wenzelm@24208
    67
wenzelm@24069
    68
wenzelm@23961
    69
(* critical section -- may be nested within the same thread *)
wenzelm@23961
    70
wenzelm@23961
    71
local
wenzelm@23961
    72
wenzelm@24063
    73
val critical_lock = Mutex.mutex ();
wenzelm@24063
    74
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
    75
val critical_name = ref "";
wenzelm@24063
    76
wenzelm@23961
    77
in
wenzelm@23961
    78
wenzelm@23961
    79
fun self_critical () =
wenzelm@23961
    80
  (case ! critical_thread of
wenzelm@23961
    81
    NONE => false
wenzelm@23961
    82
  | SOME id => Thread.equal (id, Thread.self ()));
wenzelm@23961
    83
wenzelm@23991
    84
fun NAMED_CRITICAL name e =
wenzelm@23961
    85
  if self_critical () then e ()
wenzelm@23961
    86
  else
wenzelm@24214
    87
    uninterruptible (fn atts => fn () =>
wenzelm@24208
    88
      let
wenzelm@24208
    89
        val name' = ! critical_name;
wenzelm@24208
    90
        val _ =
wenzelm@24208
    91
          if Mutex.trylock critical_lock then ()
wenzelm@24208
    92
          else
wenzelm@24208
    93
            let
wenzelm@24208
    94
              val timer = Timer.startRealTimer ();
wenzelm@24208
    95
              val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24208
    96
              val _ = Mutex.lock critical_lock;
wenzelm@24208
    97
              val time = Timer.checkRealTimer timer;
wenzelm@24208
    98
              val _ = tracing (if Time.> (time, Time.fromMilliseconds 10) then 3 else 4) (fn () =>
wenzelm@24208
    99
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   100
            in () end;
wenzelm@24208
   101
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   102
        val _ = critical_name := name;
wenzelm@24214
   103
        val result = Exn.capture (with_attributes atts (fn _ => e)) ();
wenzelm@24208
   104
        val _ = critical_name := "";
wenzelm@24208
   105
        val _ = critical_thread := NONE;
wenzelm@24208
   106
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   107
      in Exn.release result end) ();
wenzelm@23961
   108
wenzelm@23991
   109
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   110
wenzelm@23961
   111
end;
wenzelm@23961
   112
wenzelm@23973
   113
wenzelm@24208
   114
(* scheduling -- multiple threads working on a queue of tasks *)
wenzelm@24208
   115
wenzelm@24208
   116
datatype 'a task =
wenzelm@24208
   117
  Task of {body: unit -> unit, cont: 'a -> 'a, fail: 'a -> 'a} | Wait | Terminate;
wenzelm@23973
   118
wenzelm@24069
   119
local
wenzelm@24069
   120
wenzelm@24069
   121
val protected_name = ref "";
wenzelm@24069
   122
wenzelm@24069
   123
in
wenzelm@24063
   124
wenzelm@24214
   125
fun schedule n next_task = uninterruptible (fn _ => fn tasks =>
wenzelm@23973
   126
  let
wenzelm@23973
   127
    (*protected execution*)
wenzelm@23973
   128
    val lock = Mutex.mutex ();
wenzelm@24063
   129
    fun PROTECTED name e =
wenzelm@23973
   130
      let
wenzelm@24144
   131
        val name' = ! protected_name;
wenzelm@23981
   132
        val _ =
wenzelm@23981
   133
          if Mutex.trylock lock then ()
wenzelm@23981
   134
          else
wenzelm@24144
   135
            let
wenzelm@24144
   136
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24144
   137
              val _ = Mutex.lock lock;
wenzelm@24144
   138
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": passed");
wenzelm@24144
   139
            in () end;
wenzelm@24069
   140
        val _ = protected_name := name;
wenzelm@23973
   141
        val res = Exn.capture e ();
wenzelm@24069
   142
        val _ = protected_name := "";
wenzelm@23973
   143
        val _ = Mutex.unlock lock;
wenzelm@23973
   144
      in Exn.release res end;
wenzelm@23973
   145
wenzelm@24072
   146
    (*wakeup condition*)
wenzelm@24072
   147
    val wakeup = ConditionVar.conditionVar ();
wenzelm@24072
   148
    fun wakeup_all () = ConditionVar.broadcast wakeup;
wenzelm@24072
   149
    fun wait () = ConditionVar.wait (wakeup, lock);
wenzelm@24291
   150
    fun wait_timeout () = ConditionVar.waitUntil (wakeup, lock, Time.now () + Time.fromSeconds 1);
wenzelm@24072
   151
wenzelm@24214
   152
    (*queue of tasks*)
wenzelm@23973
   153
    val queue = ref tasks;
wenzelm@24072
   154
    val active = ref 0;
wenzelm@24119
   155
    fun trace_active () = tracing 1 (fn () => "SCHEDULE: " ^ Int.toString (! active) ^ " active");
wenzelm@24072
   156
    fun dequeue () =
wenzelm@23973
   157
      let
wenzelm@23981
   158
        val (next, tasks') = next_task (! queue);
wenzelm@23973
   159
        val _ = queue := tasks';
wenzelm@24072
   160
      in
wenzelm@24208
   161
        (case next of Wait =>
wenzelm@24208
   162
          (dec active; trace_active ();
wenzelm@24208
   163
            wait ();
wenzelm@24208
   164
            inc active; trace_active ();
wenzelm@24208
   165
            dequeue ())
wenzelm@24208
   166
        | _ => next)
wenzelm@24072
   167
      end;
wenzelm@23973
   168
wenzelm@24208
   169
    (*pool of running threads*)
wenzelm@23973
   170
    val status = ref ([]: exn list);
wenzelm@24208
   171
    val running = ref ([]: Thread.thread list);
wenzelm@24208
   172
    fun start f =
wenzelm@24208
   173
      (inc active;
wenzelm@24208
   174
       change running (cons (Thread.fork (f, [Thread.InterruptState Thread.InterruptDefer]))));
wenzelm@24208
   175
    fun stop () =
wenzelm@24208
   176
      (dec active;
wenzelm@24208
   177
       change running (List.filter (fn t => not (Thread.equal (t, Thread.self ())))));
wenzelm@24208
   178
wenzelm@24208
   179
   (*worker thread*)
wenzelm@24208
   180
    fun worker () =
wenzelm@24072
   181
      (case PROTECTED "dequeue" dequeue of
wenzelm@24208
   182
        Task {body, cont, fail} =>
wenzelm@24214
   183
          (case Exn.capture (interruptible (fn _ => body)) () of
wenzelm@24208
   184
            Exn.Result () =>
wenzelm@24208
   185
              (PROTECTED "cont" (fn () => (change queue cont; wakeup_all ())); worker ())
wenzelm@23981
   186
          | Exn.Exn exn =>
wenzelm@24208
   187
              PROTECTED "fail" (fn () =>
wenzelm@24208
   188
                (change status (cons exn); change queue fail; stop (); wakeup_all ())))
wenzelm@24208
   189
      | Terminate => PROTECTED "terminate" (fn () => (stop (); wakeup_all ())));
wenzelm@23973
   190
wenzelm@23973
   191
    (*main control: fork and wait*)
wenzelm@23973
   192
    fun fork 0 = ()
wenzelm@24208
   193
      | fork k = (start worker; fork (k - 1));
wenzelm@24063
   194
    val _ = PROTECTED "main" (fn () =>
wenzelm@24063
   195
     (fork (Int.max (n, 1));
wenzelm@24208
   196
      while not (List.null (! running)) do
wenzelm@24208
   197
      (trace_active ();
wenzelm@24208
   198
       if not (List.null (! status)) then (List.app Thread.interrupt (! running)) else ();
wenzelm@24291
   199
       wait_timeout ())));
wenzelm@23973
   200
wenzelm@24208
   201
  in ! status end);
wenzelm@23973
   202
wenzelm@23961
   203
end;
wenzelm@23961
   204
wenzelm@24069
   205
end;
wenzelm@24069
   206
wenzelm@23991
   207
val NAMED_CRITICAL = Multithreading.NAMED_CRITICAL;
wenzelm@23961
   208
val CRITICAL = Multithreading.CRITICAL;
wenzelm@24208
   209
wenzelm@24297
   210
fun ignore_interrupt f = Multithreading.uninterruptible (fn _ => f);
wenzelm@24297
   211
fun raise_interrupt f = Multithreading.interruptible (fn _ => f);
wenzelm@24297
   212