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