src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Thu Oct 02 21:21:21 2008 +0200 (2008-10-02)
changeset 28466 6e35fbfc32b8
parent 28465 db8667d84dd2
child 28555 d59712ee942c
permissions -rw-r--r--
with_attributes: enforces InterruptAsynch => InterruptAsynchOnce to avoid race condition;
removed pointless comments;
     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 
    36 fun tracing level msg =
    37   if level > ! trace then ()
    38   else (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
    39     handle _ (*sic*) => ();
    40 
    41 val available = true;
    42 
    43 val max_threads = ref 1;
    44 
    45 fun max_threads_value () =
    46   let val m = ! max_threads
    47   in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
    48 
    49 
    50 (* misc utils *)
    51 
    52 fun show "" = "" | show name = " " ^ name;
    53 fun show' "" = "" | show' name = " [" ^ name ^ "]";
    54 
    55 fun read_file name =
    56   let val is = TextIO.openIn name
    57   in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
    58 
    59 fun write_file name txt =
    60   let val os = TextIO.openOut name
    61   in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
    62 
    63 
    64 (* thread attributes *)
    65 
    66 val no_interrupts =
    67   [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
    68 
    69 val regular_interrupts =
    70   [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
    71 
    72 val safe_interrupts = map
    73   (fn Thread.InterruptState Thread.InterruptAsynch =>
    74       Thread.InterruptState Thread.InterruptAsynchOnce
    75     | x => x);
    76 
    77 fun with_attributes new_atts f x =
    78   let
    79     val orig_atts = Thread.getAttributes ();
    80     fun restore () = Thread.setAttributes orig_atts;
    81     val result =
    82       (Thread.setAttributes (safe_interrupts new_atts);
    83         Exn.Result (f orig_atts x) before restore ())
    84       handle e => Exn.Exn e before restore ()
    85   in Exn.release result end;
    86 
    87 fun interruptible f = with_attributes regular_interrupts (fn _ => f);
    88 
    89 fun uninterruptible f =
    90   with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
    91 
    92 
    93 (* execution with time limit *)
    94 
    95 structure TimeLimit =
    96 struct
    97 
    98 exception TimeOut;
    99 
   100 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
   101   let
   102     val worker = Thread.self ();
   103     val timeout = ref false;
   104     val watchdog = Thread.fork (fn () =>
   105       (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
   106 
   107     val result = Exn.capture (restore_attributes f) x;
   108     val was_timeout = (case result of Exn.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 _ (*sic*) => 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 Exn.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 Exn.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;