src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Mon Jul 27 17:36:30 2009 +0200 (2009-07-27)
changeset 32230 9f6461b1c9cc
parent 32186 8026b73cd357
child 32286 1fb5db48002d
permissions -rw-r--r--
interruptible: Thread.testInterrupt before changing thread attributes;
     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 (* tracing *)
    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 fun tracing_time detailed time =
    40   tracing
    41    (if not detailed then 5
    42     else if Time.>= (time, Time.fromMilliseconds 1000) then 1
    43     else if Time.>= (time, Time.fromMilliseconds 100) then 2
    44     else if Time.>= (time, Time.fromMilliseconds 10) then 3
    45     else if Time.>= (time, Time.fromMilliseconds 1) then 4 else 5);
    46 
    47 fun real_time f x =
    48   let
    49     val timer = Timer.startRealTimer ();
    50     val () = f x;
    51     val time = Timer.checkRealTimer timer;
    52   in time end;
    53 
    54 
    55 (* options *)
    56 
    57 val available = true;
    58 
    59 val max_threads = ref 0;
    60 
    61 val tested_platform =
    62   let val ml_platform = getenv "ML_PLATFORM"
    63   in String.isSuffix "linux" ml_platform orelse String.isSuffix "darwin" ml_platform end;
    64 
    65 fun max_threads_value () =
    66   let val m = ! max_threads in
    67     if m > 0 then m
    68     else if not tested_platform then 1
    69     else Int.min (Int.max (Thread.numProcessors (), 1), 8)
    70   end;
    71 
    72 fun enabled () = max_threads_value () > 1;
    73 
    74 
    75 (* misc utils *)
    76 
    77 fun show "" = "" | show name = " " ^ name;
    78 fun show' "" = "" | show' name = " [" ^ name ^ "]";
    79 
    80 fun read_file name =
    81   let val is = TextIO.openIn name
    82   in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
    83 
    84 fun write_file name txt =
    85   let val os = TextIO.openOut name
    86   in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
    87 
    88 
    89 (* thread attributes *)
    90 
    91 val no_interrupts =
    92   [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
    93 
    94 val regular_interrupts =
    95   [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
    96 
    97 val restricted_interrupts =
    98   [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptAsynchOnce];
    99 
   100 val safe_interrupts = map
   101   (fn Thread.InterruptState Thread.InterruptAsynch =>
   102       Thread.InterruptState Thread.InterruptAsynchOnce
   103     | x => x);
   104 
   105 fun with_attributes new_atts f x =
   106   let
   107     val orig_atts = safe_interrupts (Thread.getAttributes ());
   108     val result = Exn.capture (fn () =>
   109       (Thread.setAttributes (safe_interrupts new_atts); f orig_atts x)) ();
   110     val _ = Thread.setAttributes orig_atts;
   111   in Exn.release result end;
   112 
   113 fun interruptible f x =
   114   (Thread.testInterrupt (); with_attributes regular_interrupts (fn _ => fn x => f x) x);
   115 
   116 fun uninterruptible f =
   117   with_attributes no_interrupts (fn atts => fn x =>
   118     f (fn g => with_attributes atts (fn _ => fn y => g y)) x);
   119 
   120 
   121 (* execution with time limit *)
   122 
   123 structure TimeLimit =
   124 struct
   125 
   126 exception TimeOut;
   127 
   128 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
   129   let
   130     val worker = Thread.self ();
   131     val timeout = ref false;
   132     val watchdog = Thread.fork (fn () =>
   133       (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
   134 
   135     val result = Exn.capture (restore_attributes f) x;
   136     val was_timeout = (case result of Exn.Exn Exn.Interrupt => ! timeout | _ => false);
   137 
   138     val _ = Thread.interrupt watchdog handle Thread _ => ();
   139   in if was_timeout then raise TimeOut else Exn.release result end) ();
   140 
   141 end;
   142 
   143 
   144 (* system shell processes, with propagation of interrupts *)
   145 
   146 fun system_out script = uninterruptible (fn restore_attributes => fn () =>
   147   let
   148     val script_name = OS.FileSys.tmpName ();
   149     val _ = write_file script_name script;
   150 
   151     val pid_name = OS.FileSys.tmpName ();
   152     val output_name = OS.FileSys.tmpName ();
   153 
   154     (*result state*)
   155     datatype result = Wait | Signal | Result of int;
   156     val result = ref Wait;
   157     val result_mutex = Mutex.mutex ();
   158     val result_cond = ConditionVar.conditionVar ();
   159     fun set_result res =
   160       (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
   161         ConditionVar.signal result_cond);
   162 
   163     val _ = Mutex.lock result_mutex;
   164 
   165     (*system thread*)
   166     val system_thread = Thread.fork (fn () =>
   167       let
   168         val status =
   169           OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
   170             script_name ^ " " ^ pid_name ^ " " ^ output_name);
   171         val res =
   172           (case Posix.Process.fromStatus status of
   173             Posix.Process.W_EXITED => Result 0
   174           | Posix.Process.W_EXITSTATUS 0wx82 => Signal
   175           | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
   176           | Posix.Process.W_SIGNALED s =>
   177               if s = Posix.Signal.int then Signal
   178               else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
   179           | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
   180       in set_result res end handle _ (*sic*) => set_result (Result 2), []);
   181 
   182     (*main thread -- proxy for interrupts*)
   183     fun kill n =
   184       (case Int.fromString (read_file pid_name) of
   185         SOME pid =>
   186           Posix.Process.kill
   187             (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
   188               Posix.Signal.int)
   189       | NONE => ())
   190       handle OS.SysErr _ => () | IO.Io _ =>
   191         (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
   192 
   193     val _ = while ! result = Wait do
   194       restore_attributes (fn () =>
   195         (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
   196           handle Exn.Interrupt => kill 10) ();
   197 
   198     (*cleanup*)
   199     val output = read_file output_name handle IO.Io _ => "";
   200     val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
   201     val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
   202     val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
   203     val _ = Thread.interrupt system_thread handle Thread _ => ();
   204     val rc = (case ! result of Signal => raise Exn.Interrupt | Result rc => rc);
   205   in (output, rc) end) ();
   206 
   207 
   208 (* critical section -- may be nested within the same thread *)
   209 
   210 local
   211 
   212 val critical_lock = Mutex.mutex ();
   213 val critical_thread = ref (NONE: Thread.thread option);
   214 val critical_name = ref "";
   215 
   216 in
   217 
   218 fun self_critical () =
   219   (case ! critical_thread of
   220     NONE => false
   221   | SOME t => Thread.equal (t, Thread.self ()));
   222 
   223 fun NAMED_CRITICAL name e =
   224   if self_critical () then e ()
   225   else
   226     Exn.release (uninterruptible (fn restore_attributes => fn () =>
   227       let
   228         val name' = ! critical_name;
   229         val _ =
   230           if Mutex.trylock critical_lock then ()
   231           else
   232             let
   233               val _ = tracing 5 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
   234               val time = real_time Mutex.lock critical_lock;
   235               val _ = tracing_time true time (fn () =>
   236                 "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
   237             in () end;
   238         val _ = critical_thread := SOME (Thread.self ());
   239         val _ = critical_name := name;
   240         val result = Exn.capture (restore_attributes e) ();
   241         val _ = critical_name := "";
   242         val _ = critical_thread := NONE;
   243         val _ = Mutex.unlock critical_lock;
   244       in result end) ());
   245 
   246 fun CRITICAL e = NAMED_CRITICAL "" e;
   247 
   248 end;
   249 
   250 
   251 (* serial numbers *)
   252 
   253 local
   254 
   255 val serial_lock = Mutex.mutex ();
   256 val serial_count = ref 0;
   257 
   258 in
   259 
   260 val serial = uninterruptible (fn _ => fn () =>
   261   let
   262     val _ = Mutex.lock serial_lock;
   263     val _ = serial_count := ! serial_count + 1;
   264     val res = ! serial_count;
   265     val _ = Mutex.unlock serial_lock;
   266   in res end);
   267 
   268 end;
   269 
   270 end;
   271 
   272 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   273 open BasicMultithreading;