src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Sat Feb 16 16:44:02 2008 +0100 (2008-02-16 ago)
changeset 26083 abb3f8dd66dc
parent 26074 44c5419cd9f1
child 26098 b59d33f73aed
permissions -rw-r--r--
removed managed_process (cf. General/shell_process.ML);
replaced ignore/raise_interrupt by more flexible (un)interruptible combinators;
tuned timeLimit: sleep already interruptible by default;
schedule: restore attributes of body, instead of forcing interruptible execution;
wenzelm@23961
     1
(*  Title:      Pure/ML-Systems/multithreading_polyml.ML
wenzelm@23961
     2
    ID:         $Id$
wenzelm@23961
     3
    Author:     Makarius
wenzelm@23961
     4
wenzelm@25704
     5
Multithreading in Poly/ML 5.1 (cf. polyml/basis/Thread.sml).
wenzelm@23961
     6
*)
wenzelm@23961
     7
wenzelm@23961
     8
open Thread;
wenzelm@23961
     9
wenzelm@25704
    10
signature MULTITHREADING_POLYML =
wenzelm@25704
    11
sig
wenzelm@26083
    12
  val interruptible: ('a -> 'b) -> 'a -> 'b
wenzelm@26083
    13
  val uninterruptible: ((('c -> 'd) -> 'c -> 'd) -> 'a -> 'b) -> 'a -> 'b
wenzelm@25704
    14
  structure TimeLimit: TIME_LIMIT
wenzelm@25704
    15
end;
wenzelm@25704
    16
wenzelm@25704
    17
signature BASIC_MULTITHREADING =
wenzelm@25704
    18
sig
wenzelm@25704
    19
  include BASIC_MULTITHREADING
wenzelm@25704
    20
  include MULTITHREADING_POLYML
wenzelm@25704
    21
end;
wenzelm@25704
    22
wenzelm@24208
    23
signature MULTITHREADING =
wenzelm@24208
    24
sig
wenzelm@24208
    25
  include MULTITHREADING
wenzelm@25704
    26
  include MULTITHREADING_POLYML
wenzelm@24208
    27
end;
wenzelm@24208
    28
wenzelm@23961
    29
structure Multithreading: MULTITHREADING =
wenzelm@23961
    30
struct
wenzelm@23961
    31
wenzelm@24072
    32
(* options *)
wenzelm@24069
    33
wenzelm@24119
    34
val trace = ref 0;
wenzelm@24119
    35
fun tracing level msg =
wenzelm@24119
    36
  if level <= ! trace
wenzelm@23981
    37
  then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
wenzelm@23981
    38
  else ();
wenzelm@23961
    39
wenzelm@23981
    40
val available = true;
wenzelm@25775
    41
wenzelm@23973
    42
val max_threads = ref 1;
wenzelm@23973
    43
wenzelm@25775
    44
fun max_threads_value () =
wenzelm@25775
    45
  let val m = ! max_threads
wenzelm@25775
    46
  in if m <= 0 then Thread.numProcessors () else m end;
wenzelm@25775
    47
wenzelm@23973
    48
wenzelm@24069
    49
(* misc utils *)
wenzelm@24069
    50
wenzelm@24208
    51
fun cons x xs = x :: xs;
wenzelm@24069
    52
wenzelm@24208
    53
fun change r f = r := f (! r);
wenzelm@24069
    54
wenzelm@24069
    55
fun inc i = (i := ! i + 1; ! i);
wenzelm@24069
    56
fun dec i = (i := ! i - 1; ! i);
wenzelm@24069
    57
wenzelm@24208
    58
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    59
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    60
wenzelm@24208
    61
wenzelm@24208
    62
(* thread attributes *)
wenzelm@24208
    63
wenzelm@24208
    64
fun with_attributes new_atts f x =
wenzelm@24208
    65
  let
wenzelm@24208
    66
    val orig_atts = Thread.getAttributes ();
wenzelm@24208
    67
    fun restore () = Thread.setAttributes orig_atts;
wenzelm@24208
    68
  in
wenzelm@24208
    69
    Exn.release
wenzelm@24214
    70
    (*RACE for fully asynchronous interrupts!*)
wenzelm@24214
    71
    (let
wenzelm@24208
    72
        val _ = Thread.setAttributes new_atts;
wenzelm@24214
    73
        val result = Exn.capture (f orig_atts) x;
wenzelm@24208
    74
        val _ = restore ();
wenzelm@24208
    75
      in result end
wenzelm@24208
    76
      handle Interrupt => (restore (); Exn.Exn Interrupt))
wenzelm@24208
    77
  end;
wenzelm@24208
    78
wenzelm@26083
    79
fun interruptible f =
wenzelm@26083
    80
  with_attributes
wenzelm@26083
    81
    [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce]
wenzelm@26083
    82
    (fn _ => f);
wenzelm@24208
    83
wenzelm@26083
    84
fun uninterruptible f =
wenzelm@26083
    85
  with_attributes
wenzelm@26083
    86
    [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer]
wenzelm@26083
    87
    (fn atts => f (fn g => with_attributes atts (fn _ => g)));
wenzelm@24668
    88
wenzelm@24688
    89
wenzelm@24688
    90
(* execution with time limit *)
wenzelm@24688
    91
wenzelm@24688
    92
structure TimeLimit =
wenzelm@24688
    93
struct
wenzelm@24688
    94
wenzelm@24688
    95
exception TimeOut;
wenzelm@24688
    96
wenzelm@26083
    97
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
    98
  let
wenzelm@26083
    99
    val worker = Thread.self ();
wenzelm@26083
   100
    val timeout = ref false;
wenzelm@26083
   101
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   102
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   103
wenzelm@26083
   104
    (*RACE! timeout signal vs. external Interrupt*)
wenzelm@26083
   105
    val result = Exn.capture (restore_attributes f) x;
wenzelm@26083
   106
    val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
wenzelm@24688
   107
wenzelm@26083
   108
    val _ = Thread.interrupt watchdog handle Thread _ => ();
wenzelm@26083
   109
  in if was_timeout then raise TimeOut else Exn.release result end) ();
wenzelm@24688
   110
wenzelm@24688
   111
end;
wenzelm@24668
   112
wenzelm@24069
   113
wenzelm@23961
   114
(* critical section -- may be nested within the same thread *)
wenzelm@23961
   115
wenzelm@23961
   116
local
wenzelm@23961
   117
wenzelm@24063
   118
val critical_lock = Mutex.mutex ();
wenzelm@24063
   119
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
   120
val critical_name = ref "";
wenzelm@24063
   121
wenzelm@23961
   122
in
wenzelm@23961
   123
wenzelm@23961
   124
fun self_critical () =
wenzelm@23961
   125
  (case ! critical_thread of
wenzelm@23961
   126
    NONE => false
wenzelm@23961
   127
  | SOME id => Thread.equal (id, Thread.self ()));
wenzelm@23961
   128
wenzelm@23991
   129
fun NAMED_CRITICAL name e =
wenzelm@23961
   130
  if self_critical () then e ()
wenzelm@23961
   131
  else
wenzelm@26083
   132
    uninterruptible (fn restore_attributes => fn () =>
wenzelm@24208
   133
      let
wenzelm@24208
   134
        val name' = ! critical_name;
wenzelm@24208
   135
        val _ =
wenzelm@24208
   136
          if Mutex.trylock critical_lock then ()
wenzelm@24208
   137
          else
wenzelm@24208
   138
            let
wenzelm@24208
   139
              val timer = Timer.startRealTimer ();
wenzelm@24208
   140
              val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24208
   141
              val _ = Mutex.lock critical_lock;
wenzelm@24208
   142
              val time = Timer.checkRealTimer timer;
wenzelm@24208
   143
              val _ = tracing (if Time.> (time, Time.fromMilliseconds 10) then 3 else 4) (fn () =>
wenzelm@24208
   144
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   145
            in () end;
wenzelm@24208
   146
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   147
        val _ = critical_name := name;
wenzelm@26083
   148
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   149
        val _ = critical_name := "";
wenzelm@24208
   150
        val _ = critical_thread := NONE;
wenzelm@24208
   151
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   152
      in Exn.release result end) ();
wenzelm@23961
   153
wenzelm@23991
   154
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   155
wenzelm@23961
   156
end;
wenzelm@23961
   157
wenzelm@23973
   158
wenzelm@24208
   159
(* scheduling -- multiple threads working on a queue of tasks *)
wenzelm@24208
   160
wenzelm@24208
   161
datatype 'a task =
wenzelm@24208
   162
  Task of {body: unit -> unit, cont: 'a -> 'a, fail: 'a -> 'a} | Wait | Terminate;
wenzelm@23973
   163
wenzelm@26083
   164
fun schedule n next_task = uninterruptible (fn restore_attributes => fn tasks =>
wenzelm@23973
   165
  let
wenzelm@23973
   166
    (*protected execution*)
wenzelm@23973
   167
    val lock = Mutex.mutex ();
wenzelm@24672
   168
    val protected_name = ref "";
wenzelm@24063
   169
    fun PROTECTED name e =
wenzelm@23973
   170
      let
wenzelm@24144
   171
        val name' = ! protected_name;
wenzelm@23981
   172
        val _ =
wenzelm@23981
   173
          if Mutex.trylock lock then ()
wenzelm@23981
   174
          else
wenzelm@24144
   175
            let
wenzelm@24144
   176
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24144
   177
              val _ = Mutex.lock lock;
wenzelm@24144
   178
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": passed");
wenzelm@24144
   179
            in () end;
wenzelm@24069
   180
        val _ = protected_name := name;
wenzelm@23973
   181
        val res = Exn.capture e ();
wenzelm@24069
   182
        val _ = protected_name := "";
wenzelm@23973
   183
        val _ = Mutex.unlock lock;
wenzelm@23973
   184
      in Exn.release res end;
wenzelm@23973
   185
wenzelm@24072
   186
    (*wakeup condition*)
wenzelm@24072
   187
    val wakeup = ConditionVar.conditionVar ();
wenzelm@24072
   188
    fun wakeup_all () = ConditionVar.broadcast wakeup;
wenzelm@24072
   189
    fun wait () = ConditionVar.wait (wakeup, lock);
wenzelm@24291
   190
    fun wait_timeout () = ConditionVar.waitUntil (wakeup, lock, Time.now () + Time.fromSeconds 1);
wenzelm@24072
   191
wenzelm@24214
   192
    (*queue of tasks*)
wenzelm@23973
   193
    val queue = ref tasks;
wenzelm@24072
   194
    val active = ref 0;
wenzelm@24119
   195
    fun trace_active () = tracing 1 (fn () => "SCHEDULE: " ^ Int.toString (! active) ^ " active");
wenzelm@24072
   196
    fun dequeue () =
wenzelm@23973
   197
      let
wenzelm@23981
   198
        val (next, tasks') = next_task (! queue);
wenzelm@23973
   199
        val _ = queue := tasks';
wenzelm@24072
   200
      in
wenzelm@24208
   201
        (case next of Wait =>
wenzelm@24208
   202
          (dec active; trace_active ();
wenzelm@24208
   203
            wait ();
wenzelm@24208
   204
            inc active; trace_active ();
wenzelm@24208
   205
            dequeue ())
wenzelm@24208
   206
        | _ => next)
wenzelm@24072
   207
      end;
wenzelm@23973
   208
wenzelm@24208
   209
    (*pool of running threads*)
wenzelm@23973
   210
    val status = ref ([]: exn list);
wenzelm@24208
   211
    val running = ref ([]: Thread.thread list);
wenzelm@24208
   212
    fun start f =
wenzelm@24208
   213
      (inc active;
wenzelm@24208
   214
       change running (cons (Thread.fork (f, [Thread.InterruptState Thread.InterruptDefer]))));
wenzelm@24208
   215
    fun stop () =
wenzelm@24208
   216
      (dec active;
wenzelm@24208
   217
       change running (List.filter (fn t => not (Thread.equal (t, Thread.self ())))));
wenzelm@24208
   218
wenzelm@24208
   219
   (*worker thread*)
wenzelm@24208
   220
    fun worker () =
wenzelm@24072
   221
      (case PROTECTED "dequeue" dequeue of
wenzelm@24208
   222
        Task {body, cont, fail} =>
wenzelm@26083
   223
          (case Exn.capture (restore_attributes body) () of
wenzelm@24208
   224
            Exn.Result () =>
wenzelm@24208
   225
              (PROTECTED "cont" (fn () => (change queue cont; wakeup_all ())); worker ())
wenzelm@23981
   226
          | Exn.Exn exn =>
wenzelm@24208
   227
              PROTECTED "fail" (fn () =>
wenzelm@24208
   228
                (change status (cons exn); change queue fail; stop (); wakeup_all ())))
wenzelm@24208
   229
      | Terminate => PROTECTED "terminate" (fn () => (stop (); wakeup_all ())));
wenzelm@23973
   230
wenzelm@23973
   231
    (*main control: fork and wait*)
wenzelm@23973
   232
    fun fork 0 = ()
wenzelm@24208
   233
      | fork k = (start worker; fork (k - 1));
wenzelm@24063
   234
    val _ = PROTECTED "main" (fn () =>
wenzelm@24063
   235
     (fork (Int.max (n, 1));
wenzelm@24208
   236
      while not (List.null (! running)) do
wenzelm@24208
   237
      (trace_active ();
wenzelm@24208
   238
       if not (List.null (! status)) then (List.app Thread.interrupt (! running)) else ();
wenzelm@24291
   239
       wait_timeout ())));
wenzelm@23973
   240
wenzelm@24208
   241
  in ! status end);
wenzelm@23973
   242
wenzelm@25704
   243
wenzelm@25704
   244
(* serial numbers *)
wenzelm@25704
   245
wenzelm@25704
   246
local
wenzelm@25704
   247
wenzelm@25704
   248
val serial_lock = Mutex.mutex ();
wenzelm@25704
   249
val serial_count = ref 0;
wenzelm@25704
   250
wenzelm@25704
   251
in
wenzelm@25704
   252
wenzelm@25704
   253
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   254
  let
wenzelm@25704
   255
    val _ = Mutex.lock serial_lock;
wenzelm@25704
   256
    val res = inc serial_count;
wenzelm@25704
   257
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   258
  in res end);
wenzelm@25704
   259
wenzelm@23961
   260
end;
wenzelm@23961
   261
wenzelm@25735
   262
wenzelm@25735
   263
(* thread data *)
wenzelm@25735
   264
wenzelm@25735
   265
val get_data = Thread.getLocal;
wenzelm@25735
   266
val put_data = Thread.setLocal;
wenzelm@25735
   267
wenzelm@25704
   268
end;
wenzelm@24688
   269
wenzelm@25704
   270
structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@25704
   271
open BasicMultithreading;