src/Pure/ML-Systems/multithreading_polyml.ML
author wenzelm
Thu Sep 04 16:03:47 2008 +0200 (2008-09-04 ago)
changeset 28124 10a1f1f4c6ae
parent 26504 6e87c0a60104
child 28150 cbc2cbfc840c
permissions -rw-r--r--
moved Multithreading.task/schedule to Concurrent/schedule.ML;
     1 (*  Title:      Pure/ML-Systems/multithreading_polyml.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Multithreading in Poly/ML 5.1, 5.2 (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 fun tracing level msg =
    36   if level <= ! trace
    37   then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
    38   else ();
    39 
    40 val available = true;
    41 
    42 val max_threads = ref 1;
    43 
    44 fun max_threads_value () =
    45   let val m = ! max_threads
    46   in if m <= 0 then Thread.numProcessors () else m end;
    47 
    48 
    49 (* misc utils *)
    50 
    51 fun show "" = "" | show name = " " ^ name;
    52 fun show' "" = "" | show' name = " [" ^ name ^ "]";
    53 
    54 fun read_file name =
    55   let val is = TextIO.openIn name
    56   in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
    57 
    58 fun write_file name txt =
    59   let val os = TextIO.openOut name
    60   in Exn.release (Exn.capture TextIO.output (os, txt) before TextIO.closeOut os) end;
    61 
    62 
    63 (* thread attributes *)
    64 
    65 fun with_attributes new_atts f x =
    66   let
    67     val orig_atts = Thread.getAttributes ();
    68     fun restore () = Thread.setAttributes orig_atts;
    69   in
    70     Exn.release
    71     (*RACE for fully asynchronous interrupts!*)
    72     (let
    73         val _ = Thread.setAttributes new_atts;
    74         val result = Exn.capture (f orig_atts) x;
    75         val _ = restore ();
    76       in result end
    77       handle Interrupt => (restore (); Exn.Exn Interrupt))
    78   end;
    79 
    80 fun interruptible f =
    81   with_attributes
    82     [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce]
    83     (fn _ => f);
    84 
    85 fun uninterruptible f =
    86   with_attributes
    87     [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer]
    88     (fn atts => f (fn g => with_attributes atts (fn _ => g)));
    89 
    90 
    91 (* execution with time limit *)
    92 
    93 structure TimeLimit =
    94 struct
    95 
    96 exception TimeOut;
    97 
    98 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
    99   let
   100     val worker = Thread.self ();
   101     val timeout = ref false;
   102     val watchdog = Thread.fork (fn () =>
   103       (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
   104 
   105     (*RACE! timeout signal vs. external Interrupt*)
   106     val result = Exn.capture (restore_attributes f) x;
   107     val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
   108 
   109     val _ = Thread.interrupt watchdog handle Thread _ => ();
   110   in if was_timeout then raise TimeOut else Exn.release result end) ();
   111 
   112 end;
   113 
   114 
   115 (* system shell processes, with propagation of interrupts *)
   116 
   117 fun system_out_threaded script = uninterruptible (fn restore_attributes => fn () =>
   118   let
   119     val script_name = OS.FileSys.tmpName ();
   120     val _ = write_file script_name script;
   121 
   122     val pid_name = OS.FileSys.tmpName ();
   123     val output_name = OS.FileSys.tmpName ();
   124 
   125     (*result state*)
   126     datatype result = Wait | Signal | Result of int;
   127     val result = ref Wait;
   128     val result_mutex = Mutex.mutex ();
   129     val result_cond = ConditionVar.conditionVar ();
   130     fun set_result res =
   131       (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
   132         ConditionVar.signal result_cond);
   133 
   134     val _ = Mutex.lock result_mutex;
   135 
   136     (*system thread*)
   137     val system_thread = Thread.fork (fn () =>
   138       let
   139         val status =
   140           OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
   141             script_name ^ " " ^ pid_name ^ " " ^ output_name);
   142         val res =
   143           (case Posix.Process.fromStatus status of
   144             Posix.Process.W_EXITED => Result 0
   145           | Posix.Process.W_EXITSTATUS 0wx82 => Signal
   146           | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
   147           | Posix.Process.W_SIGNALED s =>
   148               if s = Posix.Signal.int then Signal
   149               else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
   150           | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
   151       in set_result res end handle _ => set_result (Result 2), []);
   152 
   153     (*main thread -- proxy for interrupts*)
   154     fun kill n =
   155       (case Int.fromString (read_file pid_name) of
   156         SOME pid =>
   157           Posix.Process.kill
   158             (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
   159               Posix.Signal.int)
   160       | NONE => ())
   161       handle OS.SysErr _ => () | IO.Io _ =>
   162         (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
   163 
   164     val _ = while ! result = Wait do
   165       restore_attributes (fn () =>
   166         (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
   167           handle Interrupt => kill 10) ();
   168 
   169     (*cleanup*)
   170     val output = read_file output_name handle IO.Io _ => "";
   171     val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
   172     val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
   173     val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
   174     val _ = Thread.interrupt system_thread handle Thread _ => ();
   175     val rc = (case ! result of Signal => raise Interrupt | Result rc => rc);
   176   in (output, rc) end) ();
   177 
   178 val system_out =
   179   if ml_system = "polyml-5.1" then system_out  (*signals not propagated from root thread!*)
   180   else system_out_threaded;
   181 
   182 
   183 (* critical section -- may be nested within the same thread *)
   184 
   185 local
   186 
   187 val critical_lock = Mutex.mutex ();
   188 val critical_thread = ref (NONE: Thread.thread option);
   189 val critical_name = ref "";
   190 
   191 in
   192 
   193 fun self_critical () =
   194   (case ! critical_thread of
   195     NONE => false
   196   | SOME id => Thread.equal (id, Thread.self ()));
   197 
   198 fun NAMED_CRITICAL name e =
   199   if self_critical () then e ()
   200   else
   201     uninterruptible (fn restore_attributes => fn () =>
   202       let
   203         val name' = ! critical_name;
   204         val _ =
   205           if Mutex.trylock critical_lock then ()
   206           else
   207             let
   208               val timer = Timer.startRealTimer ();
   209               val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
   210               val _ = Mutex.lock critical_lock;
   211               val time = Timer.checkRealTimer timer;
   212               val trace_time =
   213                 if Time.>= (time, Time.fromMilliseconds 1000) then 1
   214                 else if Time.>= (time, Time.fromMilliseconds 100) then 2
   215                 else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
   216               val _ = tracing trace_time (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 (* profiling *)
   233 
   234 local val profile_orig = profile in
   235 
   236 fun profile 0 f x = f x
   237   | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
   238 
   239 end;
   240 
   241 
   242 (* serial numbers *)
   243 
   244 local
   245 
   246 val serial_lock = Mutex.mutex ();
   247 val serial_count = ref 0;
   248 
   249 in
   250 
   251 val serial = uninterruptible (fn _ => fn () =>
   252   let
   253     val _ = Mutex.lock serial_lock;
   254     val _ = serial_count := ! serial_count + 1;
   255     val res = ! serial_count;
   256     val _ = Mutex.unlock serial_lock;
   257   in res end);
   258 
   259 end;
   260 
   261 end;
   262 
   263 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
   264 open BasicMultithreading;