1 (* Title: Pure/ML-Systems/multithreading_polyml.ML
5 Multithreading in Poly/ML 5.2 or later (cf. polyml/basis/Thread.sml).
8 signature MULTITHREADING_POLYML =
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
17 signature BASIC_MULTITHREADING =
19 include BASIC_MULTITHREADING
20 include MULTITHREADING_POLYML
23 signature MULTITHREADING =
25 include MULTITHREADING
26 include MULTITHREADING_POLYML
29 structure Multithreading: MULTITHREADING =
36 fun tracing level msg =
37 if level > ! trace then ()
38 else (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
39 handle _ (*sic*) => ();
43 val max_threads = ref 1;
45 fun max_threads_value () =
46 let val m = ! max_threads
47 in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
52 fun show "" = "" | show name = " " ^ name;
53 fun show' "" = "" | show' name = " [" ^ name ^ "]";
56 let val is = TextIO.openIn name
57 in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
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;
64 (* thread attributes *)
67 [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
69 val regular_interrupts =
70 [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
72 fun with_attributes new_atts f x =
74 val orig_atts = Thread.getAttributes ();
75 fun restore () = Thread.setAttributes orig_atts;
78 (*RACE for fully asynchronous interrupts!*)
80 val _ = Thread.setAttributes new_atts;
81 val result = Exn.capture (f orig_atts) x;
84 handle Exn.Interrupt => (restore (); Exn.Exn Exn.Interrupt))
87 fun interruptible f = with_attributes regular_interrupts (fn _ => f);
89 fun uninterruptible f =
90 with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
93 (* execution with time limit *)
100 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
102 val worker = Thread.self ();
103 val timeout = ref false;
104 val watchdog = Thread.fork (fn () =>
105 (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
107 (*RACE! timeout signal vs. external Interrupt*)
108 val result = Exn.capture (restore_attributes f) x;
109 val was_timeout = (case result of Exn.Exn Exn.Interrupt => ! timeout | _ => false);
111 val _ = Thread.interrupt watchdog handle Thread _ => ();
112 in if was_timeout then raise TimeOut else Exn.release result end) ();
117 (* system shell processes, with propagation of interrupts *)
119 fun system_out script = uninterruptible (fn restore_attributes => fn () =>
121 val script_name = OS.FileSys.tmpName ();
122 val _ = write_file script_name script;
124 val pid_name = OS.FileSys.tmpName ();
125 val output_name = OS.FileSys.tmpName ();
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 ();
133 (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
134 ConditionVar.signal result_cond);
136 val _ = Mutex.lock result_mutex;
139 val system_thread = Thread.fork (fn () =>
142 OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
143 script_name ^ " " ^ pid_name ^ " " ^ output_name);
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), []);
155 (*main thread -- proxy for interrupts*)
157 (case Int.fromString (read_file pid_name) of
160 (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
163 handle OS.SysErr _ => () | IO.Io _ =>
164 (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
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) ();
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) ();
181 (* critical section -- may be nested within the same thread *)
185 val critical_lock = Mutex.mutex ();
186 val critical_thread = ref (NONE: Thread.thread option);
187 val critical_name = ref "";
191 fun self_critical () =
192 (case ! critical_thread of
194 | SOME t => Thread.equal (t, Thread.self ()));
196 fun NAMED_CRITICAL name e =
197 if self_critical () then e ()
199 uninterruptible (fn restore_attributes => fn () =>
201 val name' = ! critical_name;
203 if Mutex.trylock critical_lock then ()
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;
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);
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) ();
225 fun CRITICAL e = NAMED_CRITICAL "" e;
232 local val profile_orig = profile in
234 fun profile 0 f x = f x
235 | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
244 val serial_lock = Mutex.mutex ();
245 val serial_count = ref 0;
249 val serial = uninterruptible (fn _ => fn () =>
251 val _ = Mutex.lock serial_lock;
252 val _ = serial_count := ! serial_count + 1;
253 val res = ! serial_count;
254 val _ = Mutex.unlock serial_lock;
261 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
262 open BasicMultithreading;