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