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 =
35 fun tracing level msg =
37 then (TextIO.output (TextIO.stdErr, (">>> " ^ msg () ^ "\n")); TextIO.flushOut TextIO.stdErr)
42 val max_threads = ref 1;
44 fun max_threads_value () =
45 let val m = ! max_threads
46 in if m <= 0 then Int.max (Thread.numProcessors (), 1) else m end;
51 fun show "" = "" | show name = " " ^ name;
52 fun show' "" = "" | show' name = " [" ^ name ^ "]";
55 let val is = TextIO.openIn name
56 in Exn.release (Exn.capture TextIO.inputAll is before TextIO.closeIn is) end;
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;
63 (* thread attributes *)
66 [Thread.EnableBroadcastInterrupt false, Thread.InterruptState Thread.InterruptDefer];
68 val regular_interrupts =
69 [Thread.EnableBroadcastInterrupt true, Thread.InterruptState Thread.InterruptAsynchOnce];
71 fun with_attributes new_atts f x =
73 val orig_atts = Thread.getAttributes ();
74 fun restore () = Thread.setAttributes orig_atts;
77 (*RACE for fully asynchronous interrupts!*)
79 val _ = Thread.setAttributes new_atts;
80 val result = Exn.capture (f orig_atts) x;
83 handle Interrupt => (restore (); Exn.Exn Interrupt))
86 fun interruptible f = with_attributes regular_interrupts (fn _ => f);
88 fun uninterruptible f =
89 with_attributes no_interrupts (fn atts => f (fn g => with_attributes atts (fn _ => g)));
92 (* execution with time limit *)
99 fun timeLimit time f x = uninterruptible (fn restore_attributes => fn () =>
101 val worker = Thread.self ();
102 val timeout = ref false;
103 val watchdog = Thread.fork (fn () =>
104 (OS.Process.sleep time; timeout := true; Thread.interrupt worker), []);
106 (*RACE! timeout signal vs. external Interrupt*)
107 val result = Exn.capture (restore_attributes f) x;
108 val was_timeout = (case result of Exn.Exn Interrupt => ! timeout | _ => false);
110 val _ = Thread.interrupt watchdog handle Thread _ => ();
111 in if was_timeout then raise TimeOut else Exn.release result end) ();
116 (* system shell processes, with propagation of interrupts *)
118 fun system_out script = uninterruptible (fn restore_attributes => fn () =>
120 val script_name = OS.FileSys.tmpName ();
121 val _ = write_file script_name script;
123 val pid_name = OS.FileSys.tmpName ();
124 val output_name = OS.FileSys.tmpName ();
127 datatype result = Wait | Signal | Result of int;
128 val result = ref Wait;
129 val result_mutex = Mutex.mutex ();
130 val result_cond = ConditionVar.conditionVar ();
132 (Mutex.lock result_mutex; result := res; Mutex.unlock result_mutex;
133 ConditionVar.signal result_cond);
135 val _ = Mutex.lock result_mutex;
138 val system_thread = Thread.fork (fn () =>
141 OS.Process.system ("perl -w \"$ISABELLE_HOME/lib/scripts/system.pl\" group " ^
142 script_name ^ " " ^ pid_name ^ " " ^ output_name);
144 (case Posix.Process.fromStatus status of
145 Posix.Process.W_EXITED => Result 0
146 | Posix.Process.W_EXITSTATUS 0wx82 => Signal
147 | Posix.Process.W_EXITSTATUS w => Result (Word8.toInt w)
148 | Posix.Process.W_SIGNALED s =>
149 if s = Posix.Signal.int then Signal
150 else Result (256 + LargeWord.toInt (Posix.Signal.toWord s))
151 | Posix.Process.W_STOPPED s => Result (512 + LargeWord.toInt (Posix.Signal.toWord s)));
152 in set_result res end handle _ => set_result (Result 2), []);
154 (*main thread -- proxy for interrupts*)
156 (case Int.fromString (read_file pid_name) of
159 (Posix.Process.K_GROUP (Posix.Process.wordToPid (LargeWord.fromInt pid)),
162 handle OS.SysErr _ => () | IO.Io _ =>
163 (OS.Process.sleep (Time.fromMilliseconds 100); if n > 0 then kill (n - 1) else ());
165 val _ = while ! result = Wait do
166 restore_attributes (fn () =>
167 (ConditionVar.waitUntil (result_cond, result_mutex, Time.now () + Time.fromMilliseconds 100); ())
168 handle Interrupt => kill 10) ();
171 val output = read_file output_name handle IO.Io _ => "";
172 val _ = OS.FileSys.remove script_name handle OS.SysErr _ => ();
173 val _ = OS.FileSys.remove pid_name handle OS.SysErr _ => ();
174 val _ = OS.FileSys.remove output_name handle OS.SysErr _ => ();
175 val _ = Thread.interrupt system_thread handle Thread _ => ();
176 val rc = (case ! result of Signal => raise Interrupt | Result rc => rc);
177 in (output, rc) end) ();
180 (* critical section -- may be nested within the same thread *)
184 val critical_lock = Mutex.mutex ();
185 val critical_thread = ref (NONE: Thread.thread option);
186 val critical_name = ref "";
190 fun self_critical () =
191 (case ! critical_thread of
193 | SOME t => Thread.equal (t, Thread.self ()));
195 fun NAMED_CRITICAL name e =
196 if self_critical () then e ()
198 uninterruptible (fn restore_attributes => fn () =>
200 val name' = ! critical_name;
202 if Mutex.trylock critical_lock then ()
205 val timer = Timer.startRealTimer ();
206 val _ = tracing 4 (fn () => "CRITICAL" ^ show name ^ show' name' ^ ": waiting");
207 val _ = Mutex.lock critical_lock;
208 val time = Timer.checkRealTimer timer;
210 if Time.>= (time, Time.fromMilliseconds 1000) then 1
211 else if Time.>= (time, Time.fromMilliseconds 100) then 2
212 else if Time.>= (time, Time.fromMilliseconds 10) then 3 else 4;
213 val _ = tracing trace_time (fn () =>
214 "CRITICAL" ^ show name ^ show' name' ^ ": passed after " ^ Time.toString time);
216 val _ = critical_thread := SOME (Thread.self ());
217 val _ = critical_name := name;
218 val result = Exn.capture (restore_attributes e) ();
219 val _ = critical_name := "";
220 val _ = critical_thread := NONE;
221 val _ = Mutex.unlock critical_lock;
222 in Exn.release result end) ();
224 fun CRITICAL e = NAMED_CRITICAL "" e;
231 local val profile_orig = profile in
233 fun profile 0 f x = f x
234 | profile n f x = NAMED_CRITICAL "profile" (fn () => profile_orig n f x);
243 val serial_lock = Mutex.mutex ();
244 val serial_count = ref 0;
248 val serial = uninterruptible (fn _ => fn () =>
250 val _ = Mutex.lock serial_lock;
251 val _ = serial_count := ! serial_count + 1;
252 val res = ! serial_count;
253 val _ = Mutex.unlock serial_lock;
260 structure BasicMultithreading: BASIC_MULTITHREADING = Multithreading;
261 open BasicMultithreading;