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