src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Sun Sep 07 22:20:15 2008 +0200 (2008-09-07)
changeset 28161 7718587e510e
parent 28150 cbc2cbfc840c
child 28169 356fc8734741
permissions -rw-r--r--
added sync_interrupts, regular_interrupts;
max_thread_value: enforce >= 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@28124
     5
Multithreading in Poly/ML 5.1, 5.2 (cf. polyml/basis/Thread.sml).
wenzelm@23961
     6
*)
wenzelm@23961
     7
wenzelm@25704
     8
signature MULTITHREADING_POLYML =
wenzelm@25704
     9
sig
wenzelm@26083
    10
  val interruptible: ('a -> 'b) -> 'a -> 'b
wenzelm@26083
    11
  val uninterruptible: ((('c -> 'd) -> 'c -> 'd) -> 'a -> 'b) -> 'a -> 'b
wenzelm@26098
    12
  val system_out: string -> string * int
wenzelm@25704
    13
  structure TimeLimit: TIME_LIMIT
wenzelm@26390
    14
  val profile: int -> ('a -> 'b) -> 'a -> 'b
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@28161
    46
  in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
wenzelm@25775
    47
wenzelm@23973
    48
wenzelm@24069
    49
(* misc utils *)
wenzelm@24069
    50
wenzelm@24208
    51
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    52
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    53
wenzelm@26098
    54
fun read_file name =
wenzelm@26098
    55
  let val is = TextIO.openIn name
wenzelm@26504
    56
  in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
wenzelm@26098
    57
wenzelm@26098
    58
fun write_file name txt =
wenzelm@26098
    59
  let val os = TextIO.openOut name
wenzelm@26504
    60
  in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
wenzelm@26098
    61
wenzelm@24208
    62
wenzelm@24208
    63
(* thread attributes *)
wenzelm@24208
    64
wenzelm@28161
    65
val no_interrupts =
wenzelm@28161
    66
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
wenzelm@28161
    67
wenzelm@28161
    68
val sync_interrupts =
wenzelm@28161
    69
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptSynch];
wenzelm@28161
    70
wenzelm@28161
    71
val regular_interrupts =
wenzelm@28161
    72
  [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
wenzelm@28161
    73
wenzelm@24208
    74
fun with_attributes new_atts f x =
wenzelm@24208
    75
  let
wenzelm@24208
    76
    val orig_atts = Thread.getAttributes ();
wenzelm@24208
    77
    fun restore () = Thread.setAttributes orig_atts;
wenzelm@24208
    78
  in
wenzelm@24208
    79
    Exn.release
wenzelm@24214
    80
    (*RACE for fully asynchronous interrupts!*)
wenzelm@24214
    81
    (let
wenzelm@24208
    82
        val _ = Thread.setAttributes new_atts;
wenzelm@24214
    83
        val result = Exn.capture (f orig_atts) x;
wenzelm@24208
    84
        val _ = restore ();
wenzelm@24208
    85
      in result end
wenzelm@24208
    86
      handle Interrupt => (restore (); Exn.Exn Interrupt))
wenzelm@24208
    87
  end;
wenzelm@24208
    88
wenzelm@28161
    89
fun interruptible f = with_attributes regular_interrupts (fn _ => f);
wenzelm@28150
    90
wenzelm@26083
    91
fun uninterruptible f =
wenzelm@28150
    92
  with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
wenzelm@24668
    93
wenzelm@24688
    94
wenzelm@24688
    95
(* execution with time limit *)
wenzelm@24688
    96
wenzelm@24688
    97
structure TimeLimit =
wenzelm@24688
    98
struct
wenzelm@24688
    99
wenzelm@24688
   100
exception TimeOut;
wenzelm@24688
   101
wenzelm@26083
   102
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
   103
  let
wenzelm@26083
   104
    val worker = Thread.self ();
wenzelm@26083
   105
    val timeout = ref false;
wenzelm@26083
   106
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   107
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   108
wenzelm@26083
   109
    (*RACE! timeout signal vs. external Interrupt*)
wenzelm@26083
   110
    val result = Exn.capture (restore_attributes f) x;
wenzelm@26083
   111
    val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
wenzelm@24688
   112
wenzelm@26083
   113
    val _ = Thread.interrupt watchdog handle Thread _ => ();
wenzelm@26083
   114
  in if was_timeout then raise TimeOut else Exn.release result end) ();
wenzelm@24688
   115
wenzelm@24688
   116
end;
wenzelm@24668
   117
wenzelm@24069
   118
wenzelm@26098
   119
(* system shell processes, with propagation of interrupts *)
wenzelm@26098
   120
wenzelm@26221
   121
fun system_out_threaded script = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26098
   122
  let
wenzelm@26098
   123
    val script_name = OS.FileSys.tmpName ();
wenzelm@26098
   124
    val _ = write_file script_name script;
wenzelm@26098
   125
wenzelm@26098
   126
    val pid_name = OS.FileSys.tmpName ();
wenzelm@26098
   127
    val output_name = OS.FileSys.tmpName ();
wenzelm@26098
   128
wenzelm@26098
   129
    (*result state*)
wenzelm@26098
   130
    datatype result = Wait | Signal | Result of int;
wenzelm@26098
   131
    val result = ref Wait;
wenzelm@26098
   132
    val result_mutex = Mutex.mutex ();
wenzelm@26098
   133
    val result_cond = ConditionVar.conditionVar ();
wenzelm@26098
   134
    fun set_result res =
wenzelm@26098
   135
      (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
wenzelm@26098
   136
        ConditionVar.signal result_cond);
wenzelm@26098
   137
wenzelm@26098
   138
    val _ = Mutex.lock result_mutex;
wenzelm@26098
   139
wenzelm@26098
   140
    (*system thread*)
wenzelm@26098
   141
    val system_thread = Thread.fork (fn () =>
wenzelm@26098
   142
      let
wenzelm@26098
   143
        val status =
wenzelm@26098
   144
          OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
wenzelm@26098
   145
            script_name ^ " " ^ pid_name ^ " " ^ output_name);
wenzelm@26098
   146
        val res =
wenzelm@26098
   147
          (case Posix.Process.fromStatus status of
wenzelm@26098
   148
            Posix.Process.W_EXITED => Result 0
wenzelm@26098
   149
          | Posix.Process.W_EXITSTATUS 0wx82 => Signal
wenzelm@26098
   150
          | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
wenzelm@26098
   151
          | Posix.Process.W_SIGNALED s =>
wenzelm@26098
   152
              if s = Posix.Signal.int then Signal
wenzelm@26098
   153
              else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
wenzelm@26098
   154
          | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
wenzelm@26098
   155
      in set_result res end handle _ => set_result (Result 2), []);
wenzelm@26098
   156
wenzelm@26098
   157
    (*main thread -- proxy for interrupts*)
wenzelm@26098
   158
    fun kill n =
wenzelm@26098
   159
      (case Int.fromString (read_file pid_name) of
wenzelm@26098
   160
        SOME pid =>
wenzelm@26098
   161
          Posix.Process.kill
wenzelm@26098
   162
            (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
wenzelm@26098
   163
              Posix.Signal.int)
wenzelm@26098
   164
      | NONE => ())
wenzelm@26098
   165
      handle OS.SysErr _ => () | IO.Io _ =>
wenzelm@26098
   166
        (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
wenzelm@26098
   167
wenzelm@26098
   168
    val _ = while ! result = Wait do
wenzelm@26098
   169
      restore_attributes (fn () =>
wenzelm@26098
   170
        (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
wenzelm@26098
   171
          handle Interrupt => kill 10) ();
wenzelm@26098
   172
wenzelm@26098
   173
    (*cleanup*)
wenzelm@26098
   174
    val output = read_file output_name handle IO.Io _ => "";
wenzelm@26098
   175
    val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
wenzelm@26098
   176
    val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
wenzelm@26098
   177
    val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
wenzelm@26098
   178
    val _ = Thread.interrupt system_thread handle Thread _ => ();
wenzelm@26098
   179
    val rc = (case ! result of Signal => raise Interrupt | Result rc => rc);
wenzelm@26098
   180
  in (output, rc) end) ();
wenzelm@26098
   181
wenzelm@26221
   182
val system_out =
wenzelm@26221
   183
  if ml_system = "polyml-5.1" then system_out  (*signals not propagated from root thread!*)
wenzelm@26221
   184
  else system_out_threaded;
wenzelm@26221
   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@28150
   200
  | SOME t => Thread.equal (t, 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@26493
   216
              val trace_time =
wenzelm@26493
   217
                if Time.>= (time, Time.fromMilliseconds 1000) then 1
wenzelm@26493
   218
                else if Time.>= (time, Time.fromMilliseconds 100) then 2
wenzelm@26493
   219
                else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
wenzelm@26493
   220
              val _ = tracing trace_time (fn () =>
wenzelm@24208
   221
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   222
            in () end;
wenzelm@24208
   223
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   224
        val _ = critical_name := name;
wenzelm@26083
   225
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   226
        val _ = critical_name := "";
wenzelm@24208
   227
        val _ = critical_thread := NONE;
wenzelm@24208
   228
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   229
      in Exn.release result end) ();
wenzelm@23961
   230
wenzelm@23991
   231
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   232
wenzelm@23961
   233
end;
wenzelm@23961
   234
wenzelm@23973
   235
wenzelm@26390
   236
(* profiling *)
wenzelm@26390
   237
wenzelm@26390
   238
local val profile_orig = profile in
wenzelm@26390
   239
wenzelm@26390
   240
fun profile 0 f x = f x
wenzelm@26390
   241
  | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
wenzelm@26390
   242
wenzelm@26390
   243
end;
wenzelm@26390
   244
wenzelm@26390
   245
wenzelm@25704
   246
(* serial numbers *)
wenzelm@25704
   247
wenzelm@25704
   248
local
wenzelm@25704
   249
wenzelm@25704
   250
val serial_lock = Mutex.mutex ();
wenzelm@25704
   251
val serial_count = ref 0;
wenzelm@25704
   252
wenzelm@25704
   253
in
wenzelm@25704
   254
wenzelm@25704
   255
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   256
  let
wenzelm@25704
   257
    val _ = Mutex.lock serial_lock;
wenzelm@28124
   258
    val _ = serial_count := ! serial_count + 1;
wenzelm@28124
   259
    val res = ! serial_count;
wenzelm@25704
   260
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   261
  in res end);
wenzelm@25704
   262
wenzelm@23961
   263
end;
wenzelm@23961
   264
wenzelm@25704
   265
end;
wenzelm@24688
   266
wenzelm@25704
   267
structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@25704
   268
open BasicMultithreading;