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