src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Sat Jul 25 00:53:47 2009 +0200 (2009-07-25 ago)
changeset 32186 8026b73cd357
parent 32185 57ecfab3bcfe
child 32230 9f6461b1c9cc
permissions -rw-r--r--
tuned tracing;
wenzelm@23961
     1
(*  Title:      Pure/ML-Systems/multithreading_polyml.ML
wenzelm@23961
     2
    Author:     Makarius
wenzelm@23961
     3
wenzelm@31311
     4
Multithreading in Poly/ML 5.2.1 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@32185
    30
(* tracing *)
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@32186
    39
fun tracing_time detailed time =
wenzelm@32184
    40
  tracing
wenzelm@32186
    41
   (if not detailed then 5
wenzelm@32186
    42
    else if Time.>= (time, Time.fromMilliseconds 1000) then 1
wenzelm@32184
    43
    else if Time.>= (time, Time.fromMilliseconds 100) then 2
wenzelm@32184
    44
    else if Time.>= (time, Time.fromMilliseconds 10) then 3
wenzelm@32184
    45
    else if Time.>= (time, Time.fromMilliseconds 1) then 4 else 5);
wenzelm@32184
    46
wenzelm@32185
    47
fun real_time f x =
wenzelm@32185
    48
  let
wenzelm@32185
    49
    val timer = Timer.startRealTimer ();
wenzelm@32185
    50
    val () = f x;
wenzelm@32185
    51
    val time = Timer.checkRealTimer timer;
wenzelm@32185
    52
  in time end;
wenzelm@32185
    53
wenzelm@32185
    54
wenzelm@32185
    55
(* options *)
wenzelm@32184
    56
wenzelm@23981
    57
val available = true;
wenzelm@25775
    58
wenzelm@31897
    59
val max_threads = ref 0;
wenzelm@23973
    60
wenzelm@31630
    61
val tested_platform =
wenzelm@31630
    62
  let val ml_platform = getenv "ML_PLATFORM"
wenzelm@31630
    63
  in String.isSuffix "linux" ml_platform orelse String.isSuffix "darwin" ml_platform end;
wenzelm@31630
    64
wenzelm@25775
    65
fun max_threads_value () =
wenzelm@31630
    66
  let val m = ! max_threads in
wenzelm@31630
    67
    if m > 0 then m
wenzelm@31630
    68
    else if not tested_platform then 1
wenzelm@31630
    69
    else Int.min (Int.max (Thread.numProcessors (), 1), 8)
wenzelm@31630
    70
  end;
wenzelm@25775
    71
wenzelm@28555
    72
fun enabled () = max_threads_value () > 1;
wenzelm@28555
    73
wenzelm@23973
    74
wenzelm@24069
    75
(* misc utils *)
wenzelm@24069
    76
wenzelm@24208
    77
fun show "" = "" | show name = " " ^ name;
wenzelm@24208
    78
fun show' "" = "" | show' name = " [" ^ name ^ "]";
wenzelm@24208
    79
wenzelm@26098
    80
fun read_file name =
wenzelm@26098
    81
  let val is = TextIO.openIn name
wenzelm@26504
    82
  in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
wenzelm@26098
    83
wenzelm@26098
    84
fun write_file name txt =
wenzelm@26098
    85
  let val os = TextIO.openOut name
wenzelm@26504
    86
  in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
wenzelm@26098
    87
wenzelm@24208
    88
wenzelm@24208
    89
(* thread attributes *)
wenzelm@24208
    90
wenzelm@28161
    91
val no_interrupts =
wenzelm@28161
    92
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
wenzelm@28161
    93
wenzelm@28161
    94
val regular_interrupts =
wenzelm@28161
    95
  [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
wenzelm@28161
    96
wenzelm@30612
    97
val restricted_interrupts =
wenzelm@30612
    98
  [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptAsynchOnce];
wenzelm@30612
    99
wenzelm@28466
   100
val safe_interrupts = map
wenzelm@28466
   101
  (fn Thread.InterruptState Thread.InterruptAsynch =>
wenzelm@28466
   102
      Thread.InterruptState Thread.InterruptAsynchOnce
wenzelm@28466
   103
    | x => x);
wenzelm@28466
   104
wenzelm@24208
   105
fun with_attributes new_atts f x =
wenzelm@24208
   106
  let
wenzelm@29550
   107
    val orig_atts = safe_interrupts (Thread.getAttributes ());
wenzelm@30602
   108
    val result = Exn.capture (fn () =>
wenzelm@30602
   109
      (Thread.setAttributes (safe_interrupts new_atts); f orig_atts x)) ();
wenzelm@30602
   110
    val _ = Thread.setAttributes orig_atts;
wenzelm@28466
   111
  in Exn.release result end;
wenzelm@24208
   112
wenzelm@32107
   113
fun interruptible f =
wenzelm@32107
   114
  with_attributes regular_interrupts (fn _ => fn x => f x);
wenzelm@28150
   115
wenzelm@26083
   116
fun uninterruptible f =
wenzelm@32107
   117
  with_attributes no_interrupts (fn atts => fn x =>
wenzelm@32107
   118
    f (fn g => with_attributes atts (fn _ => fn y => g y)) x);
wenzelm@24668
   119
wenzelm@24688
   120
wenzelm@24688
   121
(* execution with time limit *)
wenzelm@24688
   122
wenzelm@24688
   123
structure TimeLimit =
wenzelm@24688
   124
struct
wenzelm@24688
   125
wenzelm@24688
   126
exception TimeOut;
wenzelm@24688
   127
wenzelm@26083
   128
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
   129
  let
wenzelm@26083
   130
    val worker = Thread.self ();
wenzelm@26083
   131
    val timeout = ref false;
wenzelm@26083
   132
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   133
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   134
wenzelm@26083
   135
    val result = Exn.capture (restore_attributes f) x;
wenzelm@28443
   136
    val was_timeout = (case result of Exn.Exn Exn.Interrupt => ! timeout | _ => false);
wenzelm@24688
   137
wenzelm@26083
   138
    val _ = Thread.interrupt watchdog handle Thread _ => ();
wenzelm@26083
   139
  in if was_timeout then raise TimeOut else Exn.release result end) ();
wenzelm@24688
   140
wenzelm@24688
   141
end;
wenzelm@24668
   142
wenzelm@24069
   143
wenzelm@26098
   144
(* system shell processes, with propagation of interrupts *)
wenzelm@26098
   145
wenzelm@28254
   146
fun system_out script = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26098
   147
  let
wenzelm@26098
   148
    val script_name = OS.FileSys.tmpName ();
wenzelm@26098
   149
    val _ = write_file script_name script;
wenzelm@26098
   150
wenzelm@26098
   151
    val pid_name = OS.FileSys.tmpName ();
wenzelm@26098
   152
    val output_name = OS.FileSys.tmpName ();
wenzelm@26098
   153
wenzelm@26098
   154
    (*result state*)
wenzelm@26098
   155
    datatype result = Wait | Signal | Result of int;
wenzelm@26098
   156
    val result = ref Wait;
wenzelm@26098
   157
    val result_mutex = Mutex.mutex ();
wenzelm@26098
   158
    val result_cond = ConditionVar.conditionVar ();
wenzelm@26098
   159
    fun set_result res =
wenzelm@26098
   160
      (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
wenzelm@26098
   161
        ConditionVar.signal result_cond);
wenzelm@26098
   162
wenzelm@26098
   163
    val _ = Mutex.lock result_mutex;
wenzelm@26098
   164
wenzelm@26098
   165
    (*system thread*)
wenzelm@26098
   166
    val system_thread = Thread.fork (fn () =>
wenzelm@26098
   167
      let
wenzelm@26098
   168
        val status =
wenzelm@26098
   169
          OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
wenzelm@26098
   170
            script_name ^ " " ^ pid_name ^ " " ^ output_name);
wenzelm@26098
   171
        val res =
wenzelm@26098
   172
          (case Posix.Process.fromStatus status of
wenzelm@26098
   173
            Posix.Process.W_EXITED => Result 0
wenzelm@26098
   174
          | Posix.Process.W_EXITSTATUS 0wx82 => Signal
wenzelm@26098
   175
          | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
wenzelm@26098
   176
          | Posix.Process.W_SIGNALED s =>
wenzelm@26098
   177
              if s = Posix.Signal.int then Signal
wenzelm@26098
   178
              else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
wenzelm@26098
   179
          | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
wenzelm@28398
   180
      in set_result res end handle _ (*sic*) => set_result (Result 2), []);
wenzelm@26098
   181
wenzelm@26098
   182
    (*main thread -- proxy for interrupts*)
wenzelm@26098
   183
    fun kill n =
wenzelm@26098
   184
      (case Int.fromString (read_file pid_name) of
wenzelm@26098
   185
        SOME pid =>
wenzelm@26098
   186
          Posix.Process.kill
wenzelm@26098
   187
            (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
wenzelm@26098
   188
              Posix.Signal.int)
wenzelm@26098
   189
      | NONE => ())
wenzelm@26098
   190
      handle OS.SysErr _ => () | IO.Io _ =>
wenzelm@26098
   191
        (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
wenzelm@26098
   192
wenzelm@26098
   193
    val _ = while ! result = Wait do
wenzelm@26098
   194
      restore_attributes (fn () =>
wenzelm@26098
   195
        (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
wenzelm@28443
   196
          handle Exn.Interrupt => kill 10) ();
wenzelm@26098
   197
wenzelm@26098
   198
    (*cleanup*)
wenzelm@26098
   199
    val output = read_file output_name handle IO.Io _ => "";
wenzelm@26098
   200
    val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
wenzelm@26098
   201
    val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
wenzelm@26098
   202
    val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
wenzelm@26098
   203
    val _ = Thread.interrupt system_thread handle Thread _ => ();
wenzelm@28443
   204
    val rc = (case ! result of Signal => raise Exn.Interrupt | Result rc => rc);
wenzelm@26098
   205
  in (output, rc) end) ();
wenzelm@26098
   206
wenzelm@26098
   207
wenzelm@23961
   208
(* critical section -- may be nested within the same thread *)
wenzelm@23961
   209
wenzelm@23961
   210
local
wenzelm@23961
   211
wenzelm@24063
   212
val critical_lock = Mutex.mutex ();
wenzelm@24063
   213
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
   214
val critical_name = ref "";
wenzelm@24063
   215
wenzelm@23961
   216
in
wenzelm@23961
   217
wenzelm@23961
   218
fun self_critical () =
wenzelm@23961
   219
  (case ! critical_thread of
wenzelm@23961
   220
    NONE => false
wenzelm@28150
   221
  | SOME t => Thread.equal (t, Thread.self ()));
wenzelm@23961
   222
wenzelm@23991
   223
fun NAMED_CRITICAL name e =
wenzelm@23961
   224
  if self_critical () then e ()
wenzelm@23961
   225
  else
wenzelm@32184
   226
    Exn.release (uninterruptible (fn restore_attributes => fn () =>
wenzelm@24208
   227
      let
wenzelm@24208
   228
        val name' = ! critical_name;
wenzelm@24208
   229
        val _ =
wenzelm@24208
   230
          if Mutex.trylock critical_lock then ()
wenzelm@24208
   231
          else
wenzelm@24208
   232
            let
wenzelm@32184
   233
              val _ = tracing 5 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@32185
   234
              val time = real_time Mutex.lock critical_lock;
wenzelm@32186
   235
              val _ = tracing_time true time (fn () =>
wenzelm@24208
   236
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   237
            in () end;
wenzelm@24208
   238
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   239
        val _ = critical_name := name;
wenzelm@26083
   240
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   241
        val _ = critical_name := "";
wenzelm@24208
   242
        val _ = critical_thread := NONE;
wenzelm@24208
   243
        val _ = Mutex.unlock critical_lock;
wenzelm@32184
   244
      in result end) ());
wenzelm@23961
   245
wenzelm@23991
   246
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   247
wenzelm@23961
   248
end;
wenzelm@23961
   249
wenzelm@23973
   250
wenzelm@25704
   251
(* serial numbers *)
wenzelm@25704
   252
wenzelm@25704
   253
local
wenzelm@25704
   254
wenzelm@25704
   255
val serial_lock = Mutex.mutex ();
wenzelm@25704
   256
val serial_count = ref 0;
wenzelm@25704
   257
wenzelm@25704
   258
in
wenzelm@25704
   259
wenzelm@25704
   260
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   261
  let
wenzelm@25704
   262
    val _ = Mutex.lock serial_lock;
wenzelm@28124
   263
    val _ = serial_count := ! serial_count + 1;
wenzelm@28124
   264
    val res = ! serial_count;
wenzelm@25704
   265
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   266
  in res end);
wenzelm@25704
   267
wenzelm@23961
   268
end;
wenzelm@23961
   269
wenzelm@25704
   270
end;
wenzelm@24688
   271
wenzelm@25704
   272
structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@25704
   273
open BasicMultithreading;