src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Thu, 02 Oct 2008 19:59:01 +0200
changeset 28465 db8667d84dd2
parent 28443 de653f1ad78b
child 28466 6e35fbfc32b8
permissions -rw-r--r--
tracing: ignore failure of any kind;
     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 fun with_attributes new_atts f x =
    73   let
    74     val orig_atts = Thread.getAttributes ();
    75     fun restore () = Thread.setAttributes orig_atts;
    76   in
    77     Exn.release
    78     (*RACE for fully asynchronous interrupts!*)
    79     (let
    80         val _ = Thread.setAttributes new_atts;
    81         val result = Exn.capture (f orig_atts) x;
    82         val _ = restore ();
    83       in result end
    84       handle Exn.Interrupt => (restore (); Exn.Exn Exn.Interrupt))
    85   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     (*RACE! timeout signal vs. external Interrupt*)
   108     val result = Exn.capture (restore_attributes f) x;
   109     val was_timeout = (case result of Exn.Exn Exn.Interrupt => ! timeout | _ => false);
   110 
   111     val _ = Thread.interrupt watchdog handle Thread _ => ();
   112   in if was_timeout then raise TimeOut else Exn.release result end) ();
   113 
   114 end;
   115 
   116 
   117 (* system shell processes, with propagation of interrupts *)
   118 
   119 fun system_out script = uninterruptible (fn restore_attributes => fn () =>
   120   let
   121     val script_name = OS.FileSys.tmpName ();
   122     val _ = write_file script_name script;
   123 
   124     val pid_name = OS.FileSys.tmpName ();
   125     val output_name = OS.FileSys.tmpName ();
   126 
   127     (*result state*)
   128     datatype result = Wait | Signal | Result of int;
   129     val result = ref Wait;
   130     val result_mutex = Mutex.mutex ();
   131     val result_cond = ConditionVar.conditionVar ();
   132     fun set_result res =
   133       (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
   134         ConditionVar.signal result_cond);
   135 
   136     val _ = Mutex.lock result_mutex;
   137 
   138     (*system thread*)
   139     val system_thread = Thread.fork (fn () =>
   140       let
   141         val status =
   142           OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
   143             script_name ^ " " ^ pid_name ^ " " ^ output_name);
   144         val res =
   145           (case Posix.Process.fromStatus status of
   146             Posix.Process.W_EXITED => Result 0
   147           | Posix.Process.W_EXITSTATUS 0wx82 => Signal
   148           | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
   149           | Posix.Process.W_SIGNALED s =>
   150               if s = Posix.Signal.int then Signal
   151               else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
   152           | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
   153       in set_result res end handle _ (*sic*) => set_result (Result 2), []);
   154 
   155     (*main thread -- proxy for interrupts*)
   156     fun kill n =
   157       (case Int.fromString (read_file pid_name) of
   158         SOME pid =>
   159           Posix.Process.kill
   160             (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
   161               Posix.Signal.int)
   162       | NONE => ())
   163       handle OS.SysErr _ => () | IO.Io _ =>
   164         (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
   165 
   166     val _ = while ! result = Wait do
   167       restore_attributes (fn () =>
   168         (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
   169           handle Exn.Interrupt => kill 10) ();
   170 
   171     (*cleanup*)
   172     val output = read_file output_name handle IO.Io _ => "";
   173     val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
   174     val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
   175     val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
   176     val _ = Thread.interrupt system_thread handle Thread _ => ();
   177     val rc = (case ! result of Signal => raise Exn.Interrupt | Result rc => rc);
   178   in (output, rc) end) ();
   179 
   180 
   181 (* critical section -- may be nested within the same thread *)
   182 
   183 local
   184 
   185 val critical_lock = Mutex.mutex ();
   186 val critical_thread = ref (NONE: Thread.thread option);
   187 val critical_name = ref "";
   188 
   189 in
   190 
   191 fun self_critical () =
   192   (case ! critical_thread of
   193     NONE => false
   194   | SOME t => Thread.equal (t, Thread.self ()));
   195 
   196 fun NAMED_CRITICAL name e =
   197   if self_critical () then e ()
   198   else
   199     uninterruptible (fn restore_attributes => fn () =>
   200       let
   201         val name' = ! critical_name;
   202         val _ =
   203           if Mutex.trylock critical_lock then ()
   204           else
   205             let
   206               val timer = Timer.startRealTimer ();
   207               val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
   208               val _ = Mutex.lock critical_lock;
   209               val time = Timer.checkRealTimer timer;
   210               val trace_time =
   211                 if Time.>= (time, Time.fromMilliseconds 1000) then 1
   212                 else if Time.>= (time, Time.fromMilliseconds 100) then 2
   213                 else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
   214               val _ = tracing trace_time (fn () =>
   215                 "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
   216             in () end;
   217         val _ = critical_thread := SOME (Thread.self ());
   218         val _ = critical_name := name;
   219         val result = Exn.capture (restore_attributes e) ();
   220         val _ = critical_name := "";
   221         val _ = critical_thread := NONE;
   222         val _ = Mutex.unlock critical_lock;
   223       in Exn.release result end) ();
   224 
   225 fun CRITICAL e = NAMED_CRITICAL "" e;
   226 
   227 end;
   228 
   229 
   230 (* profiling *)
   231 
   232 local val profile_orig = profile in
   233 
   234 fun profile 0 f x = f x
   235   | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
   236 
   237 end;
   238 
   239 
   240 (* serial numbers *)
   241 
   242 local
   243 
   244 val serial_lock = Mutex.mutex ();
   245 val serial_count = ref 0;
   246 
   247 in
   248 
   249 val serial = uninterruptible (fn _ => fn () =>
   250   let
   251     val _ = Mutex.lock serial_lock;
   252     val _ = serial_count := ! serial_count + 1;
   253     val res = ! serial_count;
   254     val _ = Mutex.unlock serial_lock;
   255   in res end);
   256 
   257 end;
   258 
   259 end;
   260 
   261 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   262 open BasicMultithreading;