src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Sun Sep 07 17:46:41 2008 +0200 (2008-09-07 ago)
changeset 28150 cbc2cbfc840c
parent 28124 10a1f1f4c6ae
child 28161 7718587e510e
permissions -rw-r--r--
added no_interrupts;
tuned;
     1 (*  Title:      Pure/ML-Systems/multithreading_polyml.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Multithreading in Poly/ML 5.1, 5.2 (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 Thread.numProcessors () 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 fun with_attributes new_atts f x =
    66   let
    67     val orig_atts = Thread.getAttributes ();
    68     fun restore () = Thread.setAttributes orig_atts;
    69   in
    70     Exn.release
    71     (*RACE for fully asynchronous interrupts!*)
    72     (let
    73         val _ = Thread.setAttributes new_atts;
    74         val result = Exn.capture (f orig_atts) x;
    75         val _ = restore ();
    76       in result end
    77       handle Interrupt => (restore (); Exn.Exn Interrupt))
    78   end;
    79 
    80 fun interruptible f =
    81   with_attributes
    82     [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce]
    83     (fn _ => f);
    84 
    85 val no_interrupts =
    86   [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
    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_threaded 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 val system_out =
   180   if ml_system = "polyml-5.1" then system_out  (*signals not propagated from root thread!*)
   181   else system_out_threaded;
   182 
   183 
   184 (* critical section -- may be nested within the same thread *)
   185 
   186 local
   187 
   188 val critical_lock = Mutex.mutex ();
   189 val critical_thread = ref (NONE: Thread.thread option);
   190 val critical_name = ref "";
   191 
   192 in
   193 
   194 fun self_critical () =
   195   (case ! critical_thread of
   196     NONE => false
   197   | SOME t => Thread.equal (t, Thread.self ()));
   198 
   199 fun NAMED_CRITICAL name e =
   200   if self_critical () then e ()
   201   else
   202     uninterruptible (fn restore_attributes => fn () =>
   203       let
   204         val name' = ! critical_name;
   205         val _ =
   206           if Mutex.trylock critical_lock then ()
   207           else
   208             let
   209               val timer = Timer.startRealTimer ();
   210               val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
   211               val _ = Mutex.lock critical_lock;
   212               val time = Timer.checkRealTimer timer;
   213               val trace_time =
   214                 if Time.>= (time, Time.fromMilliseconds 1000) then 1
   215                 else if Time.>= (time, Time.fromMilliseconds 100) then 2
   216                 else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
   217               val _ = tracing trace_time (fn () =>
   218                 "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
   219             in () end;
   220         val _ = critical_thread := SOME (Thread.self ());
   221         val _ = critical_name := name;
   222         val result = Exn.capture (restore_attributes e) ();
   223         val _ = critical_name := "";
   224         val _ = critical_thread := NONE;
   225         val _ = Mutex.unlock critical_lock;
   226       in Exn.release result end) ();
   227 
   228 fun CRITICAL e = NAMED_CRITICAL "" e;
   229 
   230 end;
   231 
   232 
   233 (* profiling *)
   234 
   235 local val profile_orig = profile in
   236 
   237 fun profile 0 f x = f x
   238   | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
   239 
   240 end;
   241 
   242 
   243 (* serial numbers *)
   244 
   245 local
   246 
   247 val serial_lock = Mutex.mutex ();
   248 val serial_count = ref 0;
   249 
   250 in
   251 
   252 val serial = uninterruptible (fn _ => fn () =>
   253   let
   254     val _ = Mutex.lock serial_lock;
   255     val _ = serial_count := ! serial_count + 1;
   256     val res = ! serial_count;
   257     val _ = Mutex.unlock serial_lock;
   258   in res end);
   259 
   260 end;
   261 
   262 end;
   263 
   264 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   265 open BasicMultithreading;