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