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