src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Sun May 31 14:46:44 2009 +0200 (2009-05-31 ago)
changeset 31311 b82e55f51dcc
parent 30612 cb6421b6a18f
child 31630 2f8ed0dca3bd
permissions -rw-r--r--
more precise version information;
     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 1;
    42 
    43 fun max_threads_value () =
    44   let val m = ! max_threads
    45   in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
    46 
    47 fun enabled () = max_threads_value () > 1;
    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 restricted_interrupts =
    73   [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptAsynchOnce];
    74 
    75 val safe_interrupts = map
    76   (fn Thread.InterruptState Thread.InterruptAsynch =>
    77       Thread.InterruptState Thread.InterruptAsynchOnce
    78     | x => x);
    79 
    80 fun with_attributes new_atts f x =
    81   let
    82     val orig_atts = safe_interrupts (Thread.getAttributes ());
    83     val result = Exn.capture (fn () =>
    84       (Thread.setAttributes (safe_interrupts new_atts); f orig_atts x)) ();
    85     val _ = Thread.setAttributes orig_atts;
    86   in Exn.release result end;
    87 
    88 fun interruptible f = with_attributes regular_interrupts (fn _ => f);
    89 
    90 fun uninterruptible f =
    91   with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
    92 
    93 
    94 (* execution with time limit *)
    95 
    96 structure TimeLimit =
    97 struct
    98 
    99 exception TimeOut;
   100 
   101 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
   102   let
   103     val worker = Thread.self ();
   104     val timeout = ref false;
   105     val watchdog = Thread.fork (fn () =>
   106       (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
   107 
   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 (* serial numbers *)
   231 
   232 local
   233 
   234 val serial_lock = Mutex.mutex ();
   235 val serial_count = ref 0;
   236 
   237 in
   238 
   239 val serial = uninterruptible (fn _ => fn () =>
   240   let
   241     val _ = Mutex.lock serial_lock;
   242     val _ = serial_count := ! serial_count + 1;
   243     val res = ! serial_count;
   244     val _ = Mutex.unlock serial_lock;
   245   in res end);
   246 
   247 end;
   248 
   249 end;
   250 
   251 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   252 open BasicMultithreading;