src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Fri Mar 20 11:08:59 2009 +0100 (2009-03-20)
changeset 30602 1bd90b76477a
parent 29564 f8b933a62151
child 30612 cb6421b6a18f
permissions -rw-r--r--
with_attributes: canonical capture/release scheme (potentially iron out race condition);
wenzelm@23961
     1
(*  Title:      Pure/ML-Systems/multithreading_polyml.ML
wenzelm@23961
     2
    Author:     Makarius
wenzelm@23961
     3
wenzelm@28254
     4
Multithreading in Poly/ML 5.2 or later (cf. polyml/basis/Thread.sml).
wenzelm@23961
     5
*)
wenzelm@23961
     6
wenzelm@25704
     7
signature MULTITHREADING_POLYML =
wenzelm@25704
     8
sig
wenzelm@26083
     9
  val interruptible: ('a -> 'b) -> 'a -> 'b
wenzelm@26083
    10
  val uninterruptible: ((('c -> 'd) -> 'c -> 'd) -> 'a -> 'b) -> 'a -> 'b
wenzelm@26098
    11
  val system_out: string -> string * int
wenzelm@25704
    12
  structure TimeLimit: TIME_LIMIT
wenzelm@25704
    13
end;
wenzelm@25704
    14
wenzelm@25704
    15
signature BASIC_MULTITHREADING =
wenzelm@25704
    16
sig
wenzelm@25704
    17
  include BASIC_MULTITHREADING
wenzelm@25704
    18
  include MULTITHREADING_POLYML
wenzelm@25704
    19
end;
wenzelm@25704
    20
wenzelm@24208
    21
signature MULTITHREADING =
wenzelm@24208
    22
sig
wenzelm@24208
    23
  include MULTITHREADING
wenzelm@25704
    24
  include MULTITHREADING_POLYML
wenzelm@24208
    25
end;
wenzelm@24208
    26
wenzelm@23961
    27
structure Multithreading: MULTITHREADING =
wenzelm@23961
    28
struct
wenzelm@23961
    29
wenzelm@24072
    30
(* options *)
wenzelm@24069
    31
wenzelm@24119
    32
val trace = ref 0;
wenzelm@28465
    33
wenzelm@24119
    34
fun tracing level msg =
wenzelm@28465
    35
  if level > ! trace then ()
wenzelm@28465
    36
  else (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
wenzelm@28465
    37
    handle _ (*sic*) => ();
wenzelm@23961
    38
wenzelm@23981
    39
val available = true;
wenzelm@25775
    40
wenzelm@23973
    41
val max_threads = ref 1;
wenzelm@23973
    42
wenzelm@25775
    43
fun max_threads_value () =
wenzelm@25775
    44
  let val m = ! max_threads
wenzelm@28161
    45
  in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
wenzelm@25775
    46
wenzelm@28555
    47
fun enabled () = max_threads_value () > 1;
wenzelm@28555
    48
wenzelm@23973
    49
wenzelm@24069
    50
(* misc utils *)
wenzelm@24069
    51
wenzelm@24208
    52
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    53
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    54
wenzelm@26098
    55
fun read_file name =
wenzelm@26098
    56
  let val is = TextIO.openIn name
wenzelm@26504
    57
  in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
wenzelm@26098
    58
wenzelm@26098
    59
fun write_file name txt =
wenzelm@26098
    60
  let val os = TextIO.openOut name
wenzelm@26504
    61
  in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
wenzelm@26098
    62
wenzelm@24208
    63
wenzelm@24208
    64
(* thread attributes *)
wenzelm@24208
    65
wenzelm@28161
    66
val no_interrupts =
wenzelm@28161
    67
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
wenzelm@28161
    68
wenzelm@28161
    69
val regular_interrupts =
wenzelm@28161
    70
  [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
wenzelm@28161
    71
wenzelm@28466
    72
val safe_interrupts = map
wenzelm@28466
    73
  (fn Thread.InterruptState Thread.InterruptAsynch =>
wenzelm@28466
    74
      Thread.InterruptState Thread.InterruptAsynchOnce
wenzelm@28466
    75
    | x => x);
wenzelm@28466
    76
wenzelm@24208
    77
fun with_attributes new_atts f x =
wenzelm@24208
    78
  let
wenzelm@29550
    79
    val orig_atts = safe_interrupts (Thread.getAttributes ());
wenzelm@30602
    80
    val result = Exn.capture (fn () =>
wenzelm@30602
    81
      (Thread.setAttributes (safe_interrupts new_atts); f orig_atts x)) ();
wenzelm@30602
    82
    val _ = Thread.setAttributes orig_atts;
wenzelm@28466
    83
  in Exn.release result end;
wenzelm@24208
    84
wenzelm@28161
    85
fun interruptible f = with_attributes regular_interrupts (fn _ => f);
wenzelm@28150
    86
wenzelm@26083
    87
fun uninterruptible f =
wenzelm@28150
    88
  with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
wenzelm@24668
    89
wenzelm@24688
    90
wenzelm@24688
    91
(* execution with time limit *)
wenzelm@24688
    92
wenzelm@24688
    93
structure TimeLimit =
wenzelm@24688
    94
struct
wenzelm@24688
    95
wenzelm@24688
    96
exception TimeOut;
wenzelm@24688
    97
wenzelm@26083
    98
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
    99
  let
wenzelm@26083
   100
    val worker = Thread.self ();
wenzelm@26083
   101
    val timeout = ref false;
wenzelm@26083
   102
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   103
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   104
wenzelm@26083
   105
    val result = Exn.capture (restore_attributes f) x;
wenzelm@28443
   106
    val was_timeout = (case result of Exn.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@26098
   114
(* system shell processes, with propagation of interrupts *)
wenzelm@26098
   115
wenzelm@28254
   116
fun system_out script = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26098
   117
  let
wenzelm@26098
   118
    val script_name = OS.FileSys.tmpName ();
wenzelm@26098
   119
    val _ = write_file script_name script;
wenzelm@26098
   120
wenzelm@26098
   121
    val pid_name = OS.FileSys.tmpName ();
wenzelm@26098
   122
    val output_name = OS.FileSys.tmpName ();
wenzelm@26098
   123
wenzelm@26098
   124
    (*result state*)
wenzelm@26098
   125
    datatype result = Wait | Signal | Result of int;
wenzelm@26098
   126
    val result = ref Wait;
wenzelm@26098
   127
    val result_mutex = Mutex.mutex ();
wenzelm@26098
   128
    val result_cond = ConditionVar.conditionVar ();
wenzelm@26098
   129
    fun set_result res =
wenzelm@26098
   130
      (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
wenzelm@26098
   131
        ConditionVar.signal result_cond);
wenzelm@26098
   132
wenzelm@26098
   133
    val _ = Mutex.lock result_mutex;
wenzelm@26098
   134
wenzelm@26098
   135
    (*system thread*)
wenzelm@26098
   136
    val system_thread = Thread.fork (fn () =>
wenzelm@26098
   137
      let
wenzelm@26098
   138
        val status =
wenzelm@26098
   139
          OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
wenzelm@26098
   140
            script_name ^ " " ^ pid_name ^ " " ^ output_name);
wenzelm@26098
   141
        val res =
wenzelm@26098
   142
          (case Posix.Process.fromStatus status of
wenzelm@26098
   143
            Posix.Process.W_EXITED => Result 0
wenzelm@26098
   144
          | Posix.Process.W_EXITSTATUS 0wx82 => Signal
wenzelm@26098
   145
          | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
wenzelm@26098
   146
          | Posix.Process.W_SIGNALED s =>
wenzelm@26098
   147
              if s = Posix.Signal.int then Signal
wenzelm@26098
   148
              else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
wenzelm@26098
   149
          | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
wenzelm@28398
   150
      in set_result res end handle _ (*sic*) => set_result (Result 2), []);
wenzelm@26098
   151
wenzelm@26098
   152
    (*main thread -- proxy for interrupts*)
wenzelm@26098
   153
    fun kill n =
wenzelm@26098
   154
      (case Int.fromString (read_file pid_name) of
wenzelm@26098
   155
        SOME pid =>
wenzelm@26098
   156
          Posix.Process.kill
wenzelm@26098
   157
            (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
wenzelm@26098
   158
              Posix.Signal.int)
wenzelm@26098
   159
      | NONE => ())
wenzelm@26098
   160
      handle OS.SysErr _ => () | IO.Io _ =>
wenzelm@26098
   161
        (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
wenzelm@26098
   162
wenzelm@26098
   163
    val _ = while ! result = Wait do
wenzelm@26098
   164
      restore_attributes (fn () =>
wenzelm@26098
   165
        (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
wenzelm@28443
   166
          handle Exn.Interrupt => kill 10) ();
wenzelm@26098
   167
wenzelm@26098
   168
    (*cleanup*)
wenzelm@26098
   169
    val output = read_file output_name handle IO.Io _ => "";
wenzelm@26098
   170
    val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
wenzelm@26098
   171
    val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
wenzelm@26098
   172
    val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
wenzelm@26098
   173
    val _ = Thread.interrupt system_thread handle Thread _ => ();
wenzelm@28443
   174
    val rc = (case ! result of Signal => raise Exn.Interrupt | Result rc => rc);
wenzelm@26098
   175
  in (output, rc) end) ();
wenzelm@26098
   176
wenzelm@26098
   177
wenzelm@23961
   178
(* critical section -- may be nested within the same thread *)
wenzelm@23961
   179
wenzelm@23961
   180
local
wenzelm@23961
   181
wenzelm@24063
   182
val critical_lock = Mutex.mutex ();
wenzelm@24063
   183
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
   184
val critical_name = ref "";
wenzelm@24063
   185
wenzelm@23961
   186
in
wenzelm@23961
   187
wenzelm@23961
   188
fun self_critical () =
wenzelm@23961
   189
  (case ! critical_thread of
wenzelm@23961
   190
    NONE => false
wenzelm@28150
   191
  | SOME t => Thread.equal (t, Thread.self ()));
wenzelm@23961
   192
wenzelm@23991
   193
fun NAMED_CRITICAL name e =
wenzelm@23961
   194
  if self_critical () then e ()
wenzelm@23961
   195
  else
wenzelm@26083
   196
    uninterruptible (fn restore_attributes => fn () =>
wenzelm@24208
   197
      let
wenzelm@24208
   198
        val name' = ! critical_name;
wenzelm@24208
   199
        val _ =
wenzelm@24208
   200
          if Mutex.trylock critical_lock then ()
wenzelm@24208
   201
          else
wenzelm@24208
   202
            let
wenzelm@24208
   203
              val timer = Timer.startRealTimer ();
wenzelm@24208
   204
              val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@24208
   205
              val _ = Mutex.lock critical_lock;
wenzelm@24208
   206
              val time = Timer.checkRealTimer timer;
wenzelm@26493
   207
              val trace_time =
wenzelm@26493
   208
                if Time.>= (time, Time.fromMilliseconds 1000) then 1
wenzelm@26493
   209
                else if Time.>= (time, Time.fromMilliseconds 100) then 2
wenzelm@26493
   210
                else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
wenzelm@26493
   211
              val _ = tracing trace_time (fn () =>
wenzelm@24208
   212
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   213
            in () end;
wenzelm@24208
   214
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   215
        val _ = critical_name := name;
wenzelm@26083
   216
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   217
        val _ = critical_name := "";
wenzelm@24208
   218
        val _ = critical_thread := NONE;
wenzelm@24208
   219
        val _ = Mutex.unlock critical_lock;
wenzelm@24208
   220
      in Exn.release result end) ();
wenzelm@23961
   221
wenzelm@23991
   222
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   223
wenzelm@23961
   224
end;
wenzelm@23961
   225
wenzelm@23973
   226
wenzelm@25704
   227
(* serial numbers *)
wenzelm@25704
   228
wenzelm@25704
   229
local
wenzelm@25704
   230
wenzelm@25704
   231
val serial_lock = Mutex.mutex ();
wenzelm@25704
   232
val serial_count = ref 0;
wenzelm@25704
   233
wenzelm@25704
   234
in
wenzelm@25704
   235
wenzelm@25704
   236
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   237
  let
wenzelm@25704
   238
    val _ = Mutex.lock serial_lock;
wenzelm@28124
   239
    val _ = serial_count := ! serial_count + 1;
wenzelm@28124
   240
    val res = ! serial_count;
wenzelm@25704
   241
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   242
  in res end);
wenzelm@25704
   243
wenzelm@23961
   244
end;
wenzelm@23961
   245
wenzelm@25704
   246
end;
wenzelm@24688
   247
wenzelm@25704
   248
structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@25704
   249
open BasicMultithreading;