src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Thu Jul 30 23:06:06 2009 +0200 (2009-07-30 ago)
changeset 32286 1fb5db48002d
parent 32230 9f6461b1c9cc
child 32295 400cc493d466
permissions -rw-r--r--
added Multithreading.sync_wait, which turns enabled interrupts to sync ones, to ensure that wait will reaquire its lock when interrupted;
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@32286
   113
wenzelm@32286
   114
(* regular interruptibility *)
wenzelm@32286
   115
wenzelm@32230
   116
fun interruptible f x =
wenzelm@32230
   117
  (Thread.testInterrupt (); with_attributes regular_interrupts (fn _ => fn x => f x) x);
wenzelm@28150
   118
wenzelm@26083
   119
fun uninterruptible f =
wenzelm@32107
   120
  with_attributes no_interrupts (fn atts => fn x =>
wenzelm@32107
   121
    f (fn g => with_attributes atts (fn _ => fn y => g y)) x);
wenzelm@24668
   122
wenzelm@24688
   123
wenzelm@32286
   124
(* synchronous wait *)
wenzelm@32286
   125
wenzelm@32286
   126
fun sync_attributes e =
wenzelm@32286
   127
  let
wenzelm@32286
   128
    val orig_atts = Thread.getAttributes ();
wenzelm@32286
   129
    val broadcast =
wenzelm@32286
   130
      (case List.find (fn Thread.EnableBroadcastInterrupt _ => true | _ => false) orig_atts of
wenzelm@32286
   131
        NONE => Thread.EnableBroadcastInterrupt false
wenzelm@32286
   132
      | SOME att => att);
wenzelm@32286
   133
    val interrupt_state =
wenzelm@32286
   134
      (case List.find (fn Thread.InterruptState _ => true | _ => false) orig_atts of
wenzelm@32286
   135
        NONE => Thread.InterruptState Thread.InterruptDefer
wenzelm@32286
   136
      | SOME (state as Thread.InterruptState Thread.InterruptDefer) => state
wenzelm@32286
   137
      | _ => Thread.InterruptState Thread.InterruptSynch);
wenzelm@32286
   138
  in with_attributes [broadcast, interrupt_state] (fn _ => fn () => e ()) () end;
wenzelm@32286
   139
wenzelm@32286
   140
fun sync_wait time cond lock =
wenzelm@32286
   141
  sync_attributes (fn () =>
wenzelm@32286
   142
    (case time of
wenzelm@32286
   143
      SOME t => ConditionVar.waitUntil (cond, lock, t)
wenzelm@32286
   144
    | NONE => (ConditionVar.wait (cond, lock); true)));
wenzelm@32286
   145
wenzelm@32286
   146
wenzelm@24688
   147
(* execution with time limit *)
wenzelm@24688
   148
wenzelm@24688
   149
structure TimeLimit =
wenzelm@24688
   150
struct
wenzelm@24688
   151
wenzelm@24688
   152
exception TimeOut;
wenzelm@24688
   153
wenzelm@26083
   154
fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26083
   155
  let
wenzelm@26083
   156
    val worker = Thread.self ();
wenzelm@26083
   157
    val timeout = ref false;
wenzelm@26083
   158
    val watchdog = Thread.fork (fn () =>
wenzelm@26083
   159
      (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
wenzelm@24688
   160
wenzelm@26083
   161
    val result = Exn.capture (restore_attributes f) x;
wenzelm@28443
   162
    val was_timeout = (case result of Exn.Exn Exn.Interrupt => ! timeout | _ => false);
wenzelm@24688
   163
wenzelm@26083
   164
    val _ = Thread.interrupt watchdog handle Thread _ => ();
wenzelm@26083
   165
  in if was_timeout then raise TimeOut else Exn.release result end) ();
wenzelm@24688
   166
wenzelm@24688
   167
end;
wenzelm@24668
   168
wenzelm@24069
   169
wenzelm@26098
   170
(* system shell processes, with propagation of interrupts *)
wenzelm@26098
   171
wenzelm@28254
   172
fun system_out script = uninterruptible (fn restore_attributes => fn () =>
wenzelm@26098
   173
  let
wenzelm@26098
   174
    val script_name = OS.FileSys.tmpName ();
wenzelm@26098
   175
    val _ = write_file script_name script;
wenzelm@26098
   176
wenzelm@26098
   177
    val pid_name = OS.FileSys.tmpName ();
wenzelm@26098
   178
    val output_name = OS.FileSys.tmpName ();
wenzelm@26098
   179
wenzelm@26098
   180
    (*result state*)
wenzelm@26098
   181
    datatype result = Wait | Signal | Result of int;
wenzelm@26098
   182
    val result = ref Wait;
wenzelm@26098
   183
    val result_mutex = Mutex.mutex ();
wenzelm@26098
   184
    val result_cond = ConditionVar.conditionVar ();
wenzelm@26098
   185
    fun set_result res =
wenzelm@26098
   186
      (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
wenzelm@26098
   187
        ConditionVar.signal result_cond);
wenzelm@26098
   188
wenzelm@26098
   189
    val _ = Mutex.lock result_mutex;
wenzelm@26098
   190
wenzelm@26098
   191
    (*system thread*)
wenzelm@26098
   192
    val system_thread = Thread.fork (fn () =>
wenzelm@26098
   193
      let
wenzelm@26098
   194
        val status =
wenzelm@26098
   195
          OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
wenzelm@26098
   196
            script_name ^ " " ^ pid_name ^ " " ^ output_name);
wenzelm@26098
   197
        val res =
wenzelm@26098
   198
          (case Posix.Process.fromStatus status of
wenzelm@26098
   199
            Posix.Process.W_EXITED => Result 0
wenzelm@26098
   200
          | Posix.Process.W_EXITSTATUS 0wx82 => Signal
wenzelm@26098
   201
          | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
wenzelm@26098
   202
          | Posix.Process.W_SIGNALED s =>
wenzelm@26098
   203
              if s = Posix.Signal.int then Signal
wenzelm@26098
   204
              else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
wenzelm@26098
   205
          | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
wenzelm@28398
   206
      in set_result res end handle _ (*sic*) => set_result (Result 2), []);
wenzelm@26098
   207
wenzelm@26098
   208
    (*main thread -- proxy for interrupts*)
wenzelm@26098
   209
    fun kill n =
wenzelm@26098
   210
      (case Int.fromString (read_file pid_name) of
wenzelm@26098
   211
        SOME pid =>
wenzelm@26098
   212
          Posix.Process.kill
wenzelm@26098
   213
            (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
wenzelm@26098
   214
              Posix.Signal.int)
wenzelm@26098
   215
      | NONE => ())
wenzelm@26098
   216
      handle OS.SysErr _ => () | IO.Io _ =>
wenzelm@26098
   217
        (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
wenzelm@26098
   218
wenzelm@26098
   219
    val _ = while ! result = Wait do
wenzelm@26098
   220
      restore_attributes (fn () =>
wenzelm@32286
   221
        (ignore (sync_wait (SOME (Time.+ (Time.now (), Time.fromMilliseconds 100)))
wenzelm@32286
   222
            result_cond result_mutex)
wenzelm@32286
   223
          handle Exn.Interrupt => kill 10)) ();
wenzelm@26098
   224
wenzelm@26098
   225
    (*cleanup*)
wenzelm@26098
   226
    val output = read_file output_name handle IO.Io _ => "";
wenzelm@26098
   227
    val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
wenzelm@26098
   228
    val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
wenzelm@26098
   229
    val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
wenzelm@26098
   230
    val _ = Thread.interrupt system_thread handle Thread _ => ();
wenzelm@28443
   231
    val rc = (case ! result of Signal => raise Exn.Interrupt | Result rc => rc);
wenzelm@26098
   232
  in (output, rc) end) ();
wenzelm@26098
   233
wenzelm@26098
   234
wenzelm@23961
   235
(* critical section -- may be nested within the same thread *)
wenzelm@23961
   236
wenzelm@23961
   237
local
wenzelm@23961
   238
wenzelm@24063
   239
val critical_lock = Mutex.mutex ();
wenzelm@24063
   240
val critical_thread = ref (NONE: Thread.thread option);
wenzelm@24063
   241
val critical_name = ref "";
wenzelm@24063
   242
wenzelm@23961
   243
in
wenzelm@23961
   244
wenzelm@23961
   245
fun self_critical () =
wenzelm@23961
   246
  (case ! critical_thread of
wenzelm@23961
   247
    NONE => false
wenzelm@28150
   248
  | SOME t => Thread.equal (t, Thread.self ()));
wenzelm@23961
   249
wenzelm@23991
   250
fun NAMED_CRITICAL name e =
wenzelm@23961
   251
  if self_critical () then e ()
wenzelm@23961
   252
  else
wenzelm@32184
   253
    Exn.release (uninterruptible (fn restore_attributes => fn () =>
wenzelm@24208
   254
      let
wenzelm@24208
   255
        val name' = ! critical_name;
wenzelm@24208
   256
        val _ =
wenzelm@24208
   257
          if Mutex.trylock critical_lock then ()
wenzelm@24208
   258
          else
wenzelm@24208
   259
            let
wenzelm@32184
   260
              val _ = tracing 5 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
wenzelm@32185
   261
              val time = real_time Mutex.lock critical_lock;
wenzelm@32186
   262
              val _ = tracing_time true time (fn () =>
wenzelm@24208
   263
                "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
wenzelm@24208
   264
            in () end;
wenzelm@24208
   265
        val _ = critical_thread := SOME (Thread.self ());
wenzelm@24208
   266
        val _ = critical_name := name;
wenzelm@26083
   267
        val result = Exn.capture (restore_attributes e) ();
wenzelm@24208
   268
        val _ = critical_name := "";
wenzelm@24208
   269
        val _ = critical_thread := NONE;
wenzelm@24208
   270
        val _ = Mutex.unlock critical_lock;
wenzelm@32184
   271
      in result end) ());
wenzelm@23961
   272
wenzelm@23991
   273
fun CRITICAL e = NAMED_CRITICAL "" e;
wenzelm@23981
   274
wenzelm@23961
   275
end;
wenzelm@23961
   276
wenzelm@23973
   277
wenzelm@25704
   278
(* serial numbers *)
wenzelm@25704
   279
wenzelm@25704
   280
local
wenzelm@25704
   281
wenzelm@25704
   282
val serial_lock = Mutex.mutex ();
wenzelm@25704
   283
val serial_count = ref 0;
wenzelm@25704
   284
wenzelm@25704
   285
in
wenzelm@25704
   286
wenzelm@25704
   287
val serial = uninterruptible (fn _ => fn () =>
wenzelm@25704
   288
  let
wenzelm@25704
   289
    val _ = Mutex.lock serial_lock;
wenzelm@28124
   290
    val _ = serial_count := ! serial_count + 1;
wenzelm@28124
   291
    val res = ! serial_count;
wenzelm@25704
   292
    val _ = Mutex.unlock serial_lock;
wenzelm@25704
   293
  in res end);
wenzelm@25704
   294
wenzelm@23961
   295
end;
wenzelm@23961
   296
wenzelm@25704
   297
end;
wenzelm@24688
   298
wenzelm@32286
   299
structure Basic_Multithreading: BASIC_MULTITHREADING = Multithreading;
wenzelm@32286
   300
open Basic_Multithreading;