src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Tue Feb 19 20:34:30 2008 +0100 (2008-02-19 ago)
changeset 26098 b59d33f73aed
parent 26083 abb3f8dd66dc
child 26221 e557c20158e2
permissions -rw-r--r--
added system_out (back to multithreaded version -- still suffers from non-interruptible wait in Poly/ML 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@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@26098
    14
  val system_out: string -> string * int
wenzelm@25704
    15
  structure TimeLimit: TIME_LIMIT
wenzelm@25704
    16
end;
wenzelm@25704
    17
wenzelm@25704
    18
signature BASIC_MULTITHREADING =
wenzelm@25704
    19
sig
wenzelm@25704
    20
  include BASIC_MULTITHREADING
wenzelm@25704
    21
  include MULTITHREADING_POLYML
wenzelm@25704
    22
end;
wenzelm@25704
    23
wenzelm@24208
    24
signature MULTITHREADING =
wenzelm@24208
    25
sig
wenzelm@24208
    26
  include MULTITHREADING
wenzelm@25704
    27
  include MULTITHREADING_POLYML
wenzelm@24208
    28
end;
wenzelm@24208
    29
wenzelm@23961
    30
structure Multithreading: MULTITHREADING =
wenzelm@23961
    31
struct
wenzelm@23961
    32
wenzelm@24072
    33
(* options *)
wenzelm@24069
    34
wenzelm@24119
    35
val trace = ref 0;
wenzelm@24119
    36
fun tracing level msg =
wenzelm@24119
    37
  if level <= ! trace
wenzelm@23981
    38
  then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
wenzelm@23981
    39
  else ();
wenzelm@23961
    40
wenzelm@23981
    41
val available = true;
wenzelm@25775
    42
wenzelm@23973
    43
val max_threads = ref 1;
wenzelm@23973
    44
wenzelm@25775
    45
fun max_threads_value () =
wenzelm@25775
    46
  let val m = ! max_threads
wenzelm@25775
    47
  in if m <= 0 then Thread.numProcessors () else m end;
wenzelm@25775
    48
wenzelm@23973
    49
wenzelm@24069
    50
(* misc utils *)
wenzelm@24069
    51
wenzelm@24208
    52
fun cons x xs = x :: xs;
wenzelm@24069
    53
wenzelm@24208
    54
fun change r f = r := f (! r);
wenzelm@24069
    55
wenzelm@24069
    56
fun inc i = (i := ! i + 1; ! i);
wenzelm@24069
    57
fun dec i = (i := ! i - 1; ! i);
wenzelm@24069
    58
wenzelm@24208
    59
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    60
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    61
wenzelm@26098
    62
fun read_file name =
wenzelm@26098
    63
  let val is = TextIO.openIn name
wenzelm@26098
    64
  in TextIO.inputAll is before TextIO.closeIn is end;
wenzelm@26098
    65
wenzelm@26098
    66
fun write_file name txt =
wenzelm@26098
    67
  let val os = TextIO.openOut name
wenzelm@26098
    68
  in TextIO.output (os, txt) before TextIO.closeOut os end;
wenzelm@26098
    69
wenzelm@24208
    70
wenzelm@24208
    71
(* thread attributes *)
wenzelm@24208
    72
wenzelm@24208
    73
fun with_attributes new_atts f x =
wenzelm@24208
    74
  let
wenzelm@24208
    75
    val orig_atts = Thread.getAttributes ();
wenzelm@24208
    76
    fun restore () = Thread.setAttributes orig_atts;
wenzelm@24208
    77
  in
wenzelm@24208
    78
    Exn.release
wenzelm@24214
    79
    (*RACE for fully asynchronous interrupts!*)
wenzelm@24214
    80
    (let
wenzelm@24208
    81
        val _ = Thread.setAttributes new_atts;
wenzelm@24214
    82
        val result = Exn.capture (f orig_atts) x;
wenzelm@24208
    83
        val _ = restore ();
wenzelm@24208
    84
      in result end
wenzelm@24208
    85
      handle Interrupt => (restore (); Exn.Exn Interrupt))
wenzelm@24208
    86
  end;
wenzelm@24208
    87
wenzelm@26083
    88
fun interruptible f =
wenzelm@26083
    89
  with_attributes
wenzelm@26083
    90
    [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce]
wenzelm@26083
    91
    (fn _ => f);
wenzelm@24208
    92
wenzelm@26083
    93
fun uninterruptible f =
wenzelm@26083
    94
  with_attributes
wenzelm@26083
    95
    [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer]
wenzelm@26083
    96
    (fn atts => f (fn g => with_attributes atts (fn _ => g)));
wenzelm@24668
    97
wenzelm@24688
    98
wenzelm@24688
    99
(* execution with time limit *)
wenzelm@24688
   100
wenzelm@24688
   101
structure TimeLimit =
wenzelm@24688
   102
struct
wenzelm@24688
   103
wenzelm@24688
   104
exception TimeOut;
wenzelm@24688
   105
wenzelm@26083
   106
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
   107
  let
wenzelm@26083
   108
    val worker = Thread.self ();
wenzelm@26083
   109
    val timeout = ref false;
wenzelm@26083
   110
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   111
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   112
wenzelm@26083
   113
    (*RACE! timeout signal vs. external Interrupt*)
wenzelm@26083
   114
    val result = Exn.capture (restore_attributes f) x;
wenzelm@26083
   115
    val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
wenzelm@24688
   116
wenzelm@26083
   117
    val _ = Thread.interrupt watchdog handle Thread _ => ();
wenzelm@26083
   118
  in if was_timeout then raise TimeOut else Exn.release result end) ();
wenzelm@24688
   119
wenzelm@24688
   120
end;
wenzelm@24668
   121
wenzelm@24069
   122
wenzelm@26098
   123
(* system shell processes, with propagation of interrupts *)
wenzelm@26098
   124
wenzelm@26098
   125
fun system_out script = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26098
   126
  let
wenzelm@26098
   127
    val script_name = OS.FileSys.tmpName ();
wenzelm@26098
   128
    val _ = write_file script_name script;
wenzelm@26098
   129
wenzelm@26098
   130
    val pid_name = OS.FileSys.tmpName ();
wenzelm@26098
   131
    val output_name = OS.FileSys.tmpName ();
wenzelm@26098
   132
wenzelm@26098
   133
    (*result state*)
wenzelm@26098
   134
    datatype result = Wait | Signal | Result of int;
wenzelm@26098
   135
    val result = ref Wait;
wenzelm@26098
   136
    val result_mutex = Mutex.mutex ();
wenzelm@26098
   137
    val result_cond = ConditionVar.conditionVar ();
wenzelm@26098
   138
    fun set_result res =
wenzelm@26098
   139
      (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
wenzelm@26098
   140
        ConditionVar.signal result_cond);
wenzelm@26098
   141
wenzelm@26098
   142
    val _ = Mutex.lock result_mutex;
wenzelm@26098
   143
wenzelm@26098
   144
    (*system thread*)
wenzelm@26098
   145
    val system_thread = Thread.fork (fn () =>
wenzelm@26098
   146
      let
wenzelm@26098
   147
        val status =
wenzelm@26098
   148
          OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
wenzelm@26098
   149
            script_name ^ " " ^ pid_name ^ " " ^ output_name);
wenzelm@26098
   150
        val res =
wenzelm@26098
   151
          (case Posix.Process.fromStatus status of
wenzelm@26098
   152
            Posix.Process.W_EXITED => Result 0
wenzelm@26098
   153
          | Posix.Process.W_EXITSTATUS 0wx82 => Signal
wenzelm@26098
   154
          | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
wenzelm@26098
   155
          | Posix.Process.W_SIGNALED s =>
wenzelm@26098
   156
              if s = Posix.Signal.int then Signal
wenzelm@26098
   157
              else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
wenzelm@26098
   158
          | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
wenzelm@26098
   159
      in set_result res end handle _ => set_result (Result 2), []);
wenzelm@26098
   160
wenzelm@26098
   161
    (*main thread -- proxy for interrupts*)
wenzelm@26098
   162
    fun kill n =
wenzelm@26098
   163
      (case Int.fromString (read_file pid_name) of
wenzelm@26098
   164
        SOME pid =>
wenzelm@26098
   165
          Posix.Process.kill
wenzelm@26098
   166
            (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
wenzelm@26098
   167
              Posix.Signal.int)
wenzelm@26098
   168
      | NONE => ())
wenzelm@26098
   169
      handle OS.SysErr _ => () | IO.Io _ =>
wenzelm@26098
   170
        (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
wenzelm@26098
   171
wenzelm@26098
   172
    val _ = while ! result = Wait do
wenzelm@26098
   173
      restore_attributes (fn () =>
wenzelm@26098
   174
        (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
wenzelm@26098
   175
          handle Interrupt => kill 10) ();
wenzelm@26098
   176
wenzelm@26098
   177
    (*cleanup*)
wenzelm@26098
   178
    val output = read_file output_name handle IO.Io _ => "";
wenzelm@26098
   179
    val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
wenzelm@26098
   180
    val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
wenzelm@26098
   181
    val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
wenzelm@26098
   182
    val _ = Thread.interrupt system_thread handle Thread _ => ();
wenzelm@26098
   183
    val rc = (case ! result of Signal => raise Interrupt | Result rc => rc);
wenzelm@26098
   184
  in (output, rc) end) ();
wenzelm@26098
   185
wenzelm@26098
   186
wenzelm@23961
   187
(* critical section -- may be nested within the same thread *)
wenzelm@23961
   188
wenzelm@23961
   189
local
wenzelm@23961
   190
wenzelm@24063
   191
val critical_lock = Mutex.mutex ();
wenzelm@24063
   192
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
   193
val critical_name = ref "";
wenzelm@24063
   194
wenzelm@23961
   195
in
wenzelm@23961
   196
wenzelm@23961
   197
fun self_critical () =
wenzelm@23961
   198
  (case ! critical_thread of
wenzelm@23961
   199
    NONE => false
wenzelm@23961
   200
  | SOME id => Thread.equal (id, Thread.self ()));
wenzelm@23961
   201
wenzelm@23991
   202
fun NAMED_CRITICAL name e =
wenzelm@23961
   203
  if self_critical () then e ()
wenzelm@23961
   204
  else
wenzelm@26083
   205
    uninterruptible (fn restore_attributes => fn () =>
wenzelm@24208
   206
      let
wenzelm@24208
   207
        val name' = ! critical_name;
wenzelm@24208
   208
        val _ =
wenzelm@24208
   209
          if Mutex.trylock critical_lock then ()
wenzelm@24208
   210
          else
wenzelm@24208
   211
            let
wenzelm@24208
   212
              val timer = Timer.startRealTimer ();
wenzelm@24208
   213
              val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24208
   214
              val _ = Mutex.lock critical_lock;
wenzelm@24208
   215
              val time = Timer.checkRealTimer timer;
wenzelm@24208
   216
              val _ = tracing (if Time.> (time, Time.fromMilliseconds 10) then 3 else 4) (fn () =>
wenzelm@24208
   217
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   218
            in () end;
wenzelm@24208
   219
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   220
        val _ = critical_name := name;
wenzelm@26083
   221
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   222
        val _ = critical_name := "";
wenzelm@24208
   223
        val _ = critical_thread := NONE;
wenzelm@24208
   224
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   225
      in Exn.release result end) ();
wenzelm@23961
   226
wenzelm@23991
   227
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   228
wenzelm@23961
   229
end;
wenzelm@23961
   230
wenzelm@23973
   231
wenzelm@24208
   232
(* scheduling -- multiple threads working on a queue of tasks *)
wenzelm@24208
   233
wenzelm@24208
   234
datatype 'a task =
wenzelm@24208
   235
  Task of {body: unit -> unit, cont: 'a -> 'a, fail: 'a -> 'a} | Wait | Terminate;
wenzelm@23973
   236
wenzelm@26083
   237
fun schedule n next_task = uninterruptible (fn restore_attributes => fn tasks =>
wenzelm@23973
   238
  let
wenzelm@23973
   239
    (*protected execution*)
wenzelm@23973
   240
    val lock = Mutex.mutex ();
wenzelm@24672
   241
    val protected_name = ref "";
wenzelm@24063
   242
    fun PROTECTED name e =
wenzelm@23973
   243
      let
wenzelm@24144
   244
        val name' = ! protected_name;
wenzelm@23981
   245
        val _ =
wenzelm@23981
   246
          if Mutex.trylock lock then ()
wenzelm@23981
   247
          else
wenzelm@24144
   248
            let
wenzelm@24144
   249
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24144
   250
              val _ = Mutex.lock lock;
wenzelm@24144
   251
              val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": passed");
wenzelm@24144
   252
            in () end;
wenzelm@24069
   253
        val _ = protected_name := name;
wenzelm@23973
   254
        val res = Exn.capture e ();
wenzelm@24069
   255
        val _ = protected_name := "";
wenzelm@23973
   256
        val _ = Mutex.unlock lock;
wenzelm@23973
   257
      in Exn.release res end;
wenzelm@23973
   258
wenzelm@24072
   259
    (*wakeup condition*)
wenzelm@24072
   260
    val wakeup = ConditionVar.conditionVar ();
wenzelm@24072
   261
    fun wakeup_all () = ConditionVar.broadcast wakeup;
wenzelm@24072
   262
    fun wait () = ConditionVar.wait (wakeup, lock);
wenzelm@24291
   263
    fun wait_timeout () = ConditionVar.waitUntil (wakeup, lock, Time.now () + Time.fromSeconds 1);
wenzelm@24072
   264
wenzelm@24214
   265
    (*queue of tasks*)
wenzelm@23973
   266
    val queue = ref tasks;
wenzelm@24072
   267
    val active = ref 0;
wenzelm@24119
   268
    fun trace_active () = tracing 1 (fn () => "SCHEDULE: " ^ Int.toString (! active) ^ " active");
wenzelm@24072
   269
    fun dequeue () =
wenzelm@23973
   270
      let
wenzelm@23981
   271
        val (next, tasks') = next_task (! queue);
wenzelm@23973
   272
        val _ = queue := tasks';
wenzelm@24072
   273
      in
wenzelm@24208
   274
        (case next of Wait =>
wenzelm@24208
   275
          (dec active; trace_active ();
wenzelm@24208
   276
            wait ();
wenzelm@24208
   277
            inc active; trace_active ();
wenzelm@24208
   278
            dequeue ())
wenzelm@24208
   279
        | _ => next)
wenzelm@24072
   280
      end;
wenzelm@23973
   281
wenzelm@24208
   282
    (*pool of running threads*)
wenzelm@23973
   283
    val status = ref ([]: exn list);
wenzelm@24208
   284
    val running = ref ([]: Thread.thread list);
wenzelm@24208
   285
    fun start f =
wenzelm@24208
   286
      (inc active;
wenzelm@24208
   287
       change running (cons (Thread.fork (f, [Thread.InterruptState Thread.InterruptDefer]))));
wenzelm@24208
   288
    fun stop () =
wenzelm@24208
   289
      (dec active;
wenzelm@24208
   290
       change running (List.filter (fn t => not (Thread.equal (t, Thread.self ())))));
wenzelm@24208
   291
wenzelm@24208
   292
   (*worker thread*)
wenzelm@24208
   293
    fun worker () =
wenzelm@24072
   294
      (case PROTECTED "dequeue" dequeue of
wenzelm@24208
   295
        Task {body, cont, fail} =>
wenzelm@26083
   296
          (case Exn.capture (restore_attributes body) () of
wenzelm@24208
   297
            Exn.Result () =>
wenzelm@24208
   298
              (PROTECTED "cont" (fn () => (change queue cont; wakeup_all ())); worker ())
wenzelm@23981
   299
          | Exn.Exn exn =>
wenzelm@24208
   300
              PROTECTED "fail" (fn () =>
wenzelm@24208
   301
                (change status (cons exn); change queue fail; stop (); wakeup_all ())))
wenzelm@24208
   302
      | Terminate => PROTECTED "terminate" (fn () => (stop (); wakeup_all ())));
wenzelm@23973
   303
wenzelm@23973
   304
    (*main control: fork and wait*)
wenzelm@23973
   305
    fun fork 0 = ()
wenzelm@24208
   306
      | fork k = (start worker; fork (k - 1));
wenzelm@24063
   307
    val _ = PROTECTED "main" (fn () =>
wenzelm@24063
   308
     (fork (Int.max (n, 1));
wenzelm@24208
   309
      while not (List.null (! running)) do
wenzelm@24208
   310
      (trace_active ();
wenzelm@24208
   311
       if not (List.null (! status)) then (List.app Thread.interrupt (! running)) else ();
wenzelm@24291
   312
       wait_timeout ())));
wenzelm@23973
   313
wenzelm@24208
   314
  in ! status end);
wenzelm@23973
   315
wenzelm@25704
   316
wenzelm@25704
   317
(* serial numbers *)
wenzelm@25704
   318
wenzelm@25704
   319
local
wenzelm@25704
   320
wenzelm@25704
   321
val serial_lock = Mutex.mutex ();
wenzelm@25704
   322
val serial_count = ref 0;
wenzelm@25704
   323
wenzelm@25704
   324
in
wenzelm@25704
   325
wenzelm@25704
   326
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   327
  let
wenzelm@25704
   328
    val _ = Mutex.lock serial_lock;
wenzelm@25704
   329
    val res = inc serial_count;
wenzelm@25704
   330
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   331
  in res end);
wenzelm@25704
   332
wenzelm@23961
   333
end;
wenzelm@23961
   334
wenzelm@25735
   335
wenzelm@25735
   336
(* thread data *)
wenzelm@25735
   337
wenzelm@25735
   338
val get_data = Thread.getLocal;
wenzelm@25735
   339
val put_data = Thread.setLocal;
wenzelm@25735
   340
wenzelm@25704
   341
end;
wenzelm@24688
   342
wenzelm@25704
   343
structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@25704
   344
open BasicMultithreading;