src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Tue Feb 19 20:34:30 2008 +0100 (2008-02-19)
changeset 26098 b59d33f73aed
parent 26083 abb3f8dd66dc
child 26221 e557c20158e2
permissions -rw-r--r--
added system_out (back to multithreaded version -- still suffers from non-interruptible wait in Poly/ML 5.1);
     1 (*  Title:      Pure/ML-Systems/multithreading_polyml.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Multithreading in Poly/ML 5.1 (cf. polyml/basis/Thread.sml).
     6 *)
     7 
     8 open Thread;
     9 
    10 signature MULTITHREADING_POLYML =
    11 sig
    12   val interruptible: ('a -> 'b) -> 'a -> 'b
    13   val uninterruptible: ((('c -> 'd) -> 'c -> 'd) -> 'a -> 'b) -> 'a -> 'b
    14   val system_out: string -> string * int
    15   structure TimeLimit: TIME_LIMIT
    16 end;
    17 
    18 signature BASIC_MULTITHREADING =
    19 sig
    20   include BASIC_MULTITHREADING
    21   include MULTITHREADING_POLYML
    22 end;
    23 
    24 signature MULTITHREADING =
    25 sig
    26   include MULTITHREADING
    27   include MULTITHREADING_POLYML
    28 end;
    29 
    30 structure Multithreading: MULTITHREADING =
    31 struct
    32 
    33 (* options *)
    34 
    35 val trace = ref 0;
    36 fun tracing level msg =
    37   if level <= ! trace
    38   then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
    39   else ();
    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 Thread.numProcessors () else m end;
    48 
    49 
    50 (* misc utils *)
    51 
    52 fun cons x xs = x :: xs;
    53 
    54 fun change r f = r := f (! r);
    55 
    56 fun inc i = (i := ! i + 1; ! i);
    57 fun dec i = (i := ! i - 1; ! i);
    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 TextIO.inputAll is before TextIO.closeIn is end;
    65 
    66 fun write_file name txt =
    67   let val os = TextIO.openOut name
    68   in TextIO.output (os, txt) before TextIO.closeOut os end;
    69 
    70 
    71 (* thread attributes *)
    72 
    73 fun with_attributes new_atts f x =
    74   let
    75     val orig_atts = Thread.getAttributes ();
    76     fun restore () = Thread.setAttributes orig_atts;
    77   in
    78     Exn.release
    79     (*RACE for fully asynchronous interrupts!*)
    80     (let
    81         val _ = Thread.setAttributes new_atts;
    82         val result = Exn.capture (f orig_atts) x;
    83         val _ = restore ();
    84       in result end
    85       handle Interrupt => (restore (); Exn.Exn Interrupt))
    86   end;
    87 
    88 fun interruptible f =
    89   with_attributes
    90     [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce]
    91     (fn _ => f);
    92 
    93 fun uninterruptible f =
    94   with_attributes
    95     [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer]
    96     (fn atts => f (fn g => with_attributes atts (fn _ => g)));
    97 
    98 
    99 (* execution with time limit *)
   100 
   101 structure TimeLimit =
   102 struct
   103 
   104 exception TimeOut;
   105 
   106 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
   107   let
   108     val worker = Thread.self ();
   109     val timeout = ref false;
   110     val watchdog = Thread.fork (fn () =>
   111       (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
   112 
   113     (*RACE! timeout signal vs. external Interrupt*)
   114     val result = Exn.capture (restore_attributes f) x;
   115     val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
   116 
   117     val _ = Thread.interrupt watchdog handle Thread _ => ();
   118   in if was_timeout then raise TimeOut else Exn.release result end) ();
   119 
   120 end;
   121 
   122 
   123 (* system shell processes, with propagation of interrupts *)
   124 
   125 fun system_out script = uninterruptible (fn restore_attributes => fn () =>
   126   let
   127     val script_name = OS.FileSys.tmpName ();
   128     val _ = write_file script_name script;
   129 
   130     val pid_name = OS.FileSys.tmpName ();
   131     val output_name = OS.FileSys.tmpName ();
   132 
   133     (*result state*)
   134     datatype result = Wait | Signal | Result of int;
   135     val result = ref Wait;
   136     val result_mutex = Mutex.mutex ();
   137     val result_cond = ConditionVar.conditionVar ();
   138     fun set_result res =
   139       (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
   140         ConditionVar.signal result_cond);
   141 
   142     val _ = Mutex.lock result_mutex;
   143 
   144     (*system thread*)
   145     val system_thread = Thread.fork (fn () =>
   146       let
   147         val status =
   148           OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
   149             script_name ^ " " ^ pid_name ^ " " ^ output_name);
   150         val res =
   151           (case Posix.Process.fromStatus status of
   152             Posix.Process.W_EXITED => Result 0
   153           | Posix.Process.W_EXITSTATUS 0wx82 => Signal
   154           | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
   155           | Posix.Process.W_SIGNALED s =>
   156               if s = Posix.Signal.int then Signal
   157               else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
   158           | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
   159       in set_result res end handle _ => set_result (Result 2), []);
   160 
   161     (*main thread -- proxy for interrupts*)
   162     fun kill n =
   163       (case Int.fromString (read_file pid_name) of
   164         SOME pid =>
   165           Posix.Process.kill
   166             (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
   167               Posix.Signal.int)
   168       | NONE => ())
   169       handle OS.SysErr _ => () | IO.Io _ =>
   170         (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
   171 
   172     val _ = while ! result = Wait do
   173       restore_attributes (fn () =>
   174         (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
   175           handle Interrupt => kill 10) ();
   176 
   177     (*cleanup*)
   178     val output = read_file output_name handle IO.Io _ => "";
   179     val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
   180     val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
   181     val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
   182     val _ = Thread.interrupt system_thread handle Thread _ => ();
   183     val rc = (case ! result of Signal => raise Interrupt | Result rc => rc);
   184   in (output, rc) end) ();
   185 
   186 
   187 (* critical section -- may be nested within the same thread *)
   188 
   189 local
   190 
   191 val critical_lock = Mutex.mutex ();
   192 val critical_thread = ref (NONE: Thread.thread option);
   193 val critical_name = ref "";
   194 
   195 in
   196 
   197 fun self_critical () =
   198   (case ! critical_thread of
   199     NONE => false
   200   | SOME id => Thread.equal (id, Thread.self ()));
   201 
   202 fun NAMED_CRITICAL name e =
   203   if self_critical () then e ()
   204   else
   205     uninterruptible (fn restore_attributes => fn () =>
   206       let
   207         val name' = ! critical_name;
   208         val _ =
   209           if Mutex.trylock critical_lock then ()
   210           else
   211             let
   212               val timer = Timer.startRealTimer ();
   213               val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
   214               val _ = Mutex.lock critical_lock;
   215               val time = Timer.checkRealTimer timer;
   216               val _ = tracing (if Time.> (time, Time.fromMilliseconds 10) then 3 else 4) (fn () =>
   217                 "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
   218             in () end;
   219         val _ = critical_thread := SOME (Thread.self ());
   220         val _ = critical_name := name;
   221         val result = Exn.capture (restore_attributes e) ();
   222         val _ = critical_name := "";
   223         val _ = critical_thread := NONE;
   224         val _ = Mutex.unlock critical_lock;
   225       in Exn.release result end) ();
   226 
   227 fun CRITICAL e = NAMED_CRITICAL "" e;
   228 
   229 end;
   230 
   231 
   232 (* scheduling -- multiple threads working on a queue of tasks *)
   233 
   234 datatype 'a task =
   235   Task of {body: unit -> unit, cont: 'a -> 'a, fail: 'a -> 'a} | Wait | Terminate;
   236 
   237 fun schedule n next_task = uninterruptible (fn restore_attributes => fn tasks =>
   238   let
   239     (*protected execution*)
   240     val lock = Mutex.mutex ();
   241     val protected_name = ref "";
   242     fun PROTECTED name e =
   243       let
   244         val name' = ! protected_name;
   245         val _ =
   246           if Mutex.trylock lock then ()
   247           else
   248             let
   249               val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": waiting");
   250               val _ = Mutex.lock lock;
   251               val _ = tracing 2 (fn () => "PROTECTED" ^ show name ^ show' name' ^ ": passed");
   252             in () end;
   253         val _ = protected_name := name;
   254         val res = Exn.capture e ();
   255         val _ = protected_name := "";
   256         val _ = Mutex.unlock lock;
   257       in Exn.release res end;
   258 
   259     (*wakeup condition*)
   260     val wakeup = ConditionVar.conditionVar ();
   261     fun wakeup_all () = ConditionVar.broadcast wakeup;
   262     fun wait () = ConditionVar.wait (wakeup, lock);
   263     fun wait_timeout () = ConditionVar.waitUntil (wakeup, lock, Time.now () + Time.fromSeconds 1);
   264 
   265     (*queue of tasks*)
   266     val queue = ref tasks;
   267     val active = ref 0;
   268     fun trace_active () = tracing 1 (fn () => "SCHEDULE: " ^ Int.toString (! active) ^ " active");
   269     fun dequeue () =
   270       let
   271         val (next, tasks') = next_task (! queue);
   272         val _ = queue := tasks';
   273       in
   274         (case next of Wait =>
   275           (dec active; trace_active ();
   276             wait ();
   277             inc active; trace_active ();
   278             dequeue ())
   279         | _ => next)
   280       end;
   281 
   282     (*pool of running threads*)
   283     val status = ref ([]: exn list);
   284     val running = ref ([]: Thread.thread list);
   285     fun start f =
   286       (inc active;
   287        change running (cons (Thread.fork (f, [Thread.InterruptState Thread.InterruptDefer]))));
   288     fun stop () =
   289       (dec active;
   290        change running (List.filter (fn t => not (Thread.equal (t, Thread.self ())))));
   291 
   292    (*worker thread*)
   293     fun worker () =
   294       (case PROTECTED "dequeue" dequeue of
   295         Task {body, cont, fail} =>
   296           (case Exn.capture (restore_attributes body) () of
   297             Exn.Result () =>
   298               (PROTECTED "cont" (fn () => (change queue cont; wakeup_all ())); worker ())
   299           | Exn.Exn exn =>
   300               PROTECTED "fail" (fn () =>
   301                 (change status (cons exn); change queue fail; stop (); wakeup_all ())))
   302       | Terminate => PROTECTED "terminate" (fn () => (stop (); wakeup_all ())));
   303 
   304     (*main control: fork and wait*)
   305     fun fork 0 = ()
   306       | fork k = (start worker; fork (k - 1));
   307     val _ = PROTECTED "main" (fn () =>
   308      (fork (Int.max (n, 1));
   309       while not (List.null (! running)) do
   310       (trace_active ();
   311        if not (List.null (! status)) then (List.app Thread.interrupt (! running)) else ();
   312        wait_timeout ())));
   313 
   314   in ! status end);
   315 
   316 
   317 (* serial numbers *)
   318 
   319 local
   320 
   321 val serial_lock = Mutex.mutex ();
   322 val serial_count = ref 0;
   323 
   324 in
   325 
   326 val serial = uninterruptible (fn _ => fn () =>
   327   let
   328     val _ = Mutex.lock serial_lock;
   329     val res = inc serial_count;
   330     val _ = Mutex.unlock serial_lock;
   331   in res end);
   332 
   333 end;
   334 
   335 
   336 (* thread data *)
   337 
   338 val get_data = Thread.getLocal;
   339 val put_data = Thread.setLocal;
   340 
   341 end;
   342 
   343 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   344 open BasicMultithreading;