4343 type 'a t
4444
4545 val make : unit -> 'a t
46- val get : 'a t -> 'a
46+ val get : 'a t -> ( 'a , unit ) result
4747 val set : 'a t -> 'a -> unit
48+ val kill : 'a t -> unit
4849end =
4950struct
5051 type 'a t = {
5152 m : Mutex .t ;
5253 cv : Condition .t ;
53- mutable cell : 'a option ;
54+ mutable cell : ( 'a , unit ) result option ;
5455 }
5556
5657 let make () = { m = Mutex. create () ; cv = Condition. create () ; cell = None }
@@ -71,7 +72,13 @@ struct
7172
7273 let set t v =
7374 Mutex. lock t.m;
74- t.cell < - Some v;
75+ t.cell < - Some (Ok v);
76+ Mutex. unlock t.m;
77+ Condition. signal t.cv
78+
79+ let kill t =
80+ Mutex. lock t.m;
81+ t.cell < - Some (Error () );
7582 Mutex. unlock t.m;
7683 Condition. signal t.cv
7784end
@@ -97,14 +104,16 @@ let waiters : thread Lwt.u Lwt_sequence.t Domain.DLS.key = Domain.DLS.new_key Lw
97104
98105(* Code executed by a worker: *)
99106let rec worker_loop worker =
100- let id, task = CELL. get worker.task_cell in
101- task () ;
102- (* If there is too much threads, exit. This can happen if the user
103- decreased the maximum: *)
104- if Domain.DLS. get threads_count > Domain.DLS. get max_threads then worker.reuse < - false ;
105- (* Tell the main thread that work is done: *)
106- Lwt_unix. send_notification id;
107- if worker.reuse then worker_loop worker
107+ match CELL. get worker.task_cell with
108+ | Error () -> ()
109+ | Ok (id , task ) ->
110+ task () ;
111+ (* If there is too much threads, exit. This can happen if the user
112+ decreased the maximum: *)
113+ if Domain.DLS. get threads_count > Domain.DLS. get max_threads then worker.reuse < - false ;
114+ (* Tell the main thread that work is done: *)
115+ Lwt_unix. send_notification id;
116+ if worker.reuse then worker_loop worker
108117
109118(* create a new worker: *)
110119let make_worker () =
@@ -258,10 +267,14 @@ let run_in_domain d f =
258267 run_in_domain_dont_wait d job;
259268 (* Wait for the result. *)
260269 match CELL. get cell with
261- | Result. Ok ret -> ret
262- | Result. Error exn -> raise exn
270+ | Ok (Ok ret ) -> ret
271+ | Ok (Error exn ) -> raise exn
272+ | Error () -> assert false
263273
264274(* This version shadows the one above, adding an exception handler *)
265275let run_in_domain_dont_wait d f handler =
266276 let f () = Lwt. catch f (fun exc -> handler exc; Lwt. return_unit) in
267277 run_in_domain_dont_wait d f
278+
279+ let kill_all () =
280+ Queue. iter (fun thread -> CELL. kill thread.task_cell) (Domain.DLS. get workers)
0 commit comments