feat(picos): add shutdown and max_fds

This commit is contained in:
Simon Cruanes 2025-05-01 11:22:32 -04:00
parent 3125f3274b
commit 4c3c53ee16
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 36 additions and 5 deletions

View file

@ -55,10 +55,24 @@ module Global_ = struct
nanoev = ev; nanoev = ev;
th = Thread.create (bg_thread_ ~active ~evloop:ev) (); th = Thread.create (bg_thread_ ~active ~evloop:ev) ();
} }
let shutdown_bg_thread () =
let@ () = with_lock lock in
match Atomic.exchange st None with
| None -> ()
| Some st ->
Atomic.set st.active false;
Nanoev.wakeup_from_outside st.nanoev;
Thread.join st.th
end end
let has_bg_thread = Global_.has_bg_thread let has_bg_thread = Global_.has_bg_thread
let setup_bg_thread = Global_.setup_bg_thread let setup_bg_thread = Global_.setup_bg_thread
let shutdown_bg_thread = Global_.shutdown_bg_thread
let with_setup_bg_thread ev f =
setup_bg_thread ev;
Fun.protect ~finally:shutdown_bg_thread f
let[@inline] get_loop_exn_ () : Nanoev.t = let[@inline] get_loop_exn_ () : Nanoev.t =
match Atomic.get Global_.st with match Atomic.get Global_.st with
@ -136,6 +150,11 @@ let write fd buf i len : int =
let connect fd addr = retry_write_ fd (fun () -> Unix.connect fd addr) let connect fd addr = retry_write_ fd (fun () -> Unix.connect fd addr)
let[@inline] max_fds () =
match Atomic.get Global_.st with
| None -> 1024
| Some st -> Nanoev.max_fds st.nanoev
let sleep t = let sleep t =
if t > 0. then ( if t > 0. then (
let ev = get_loop_exn_ () in let ev = get_loop_exn_ () in

View file

@ -1,11 +1,18 @@
(** Basic interface with picos *) (** Basic interface with picos *)
val setup_bg_thread : Nanoev.t -> unit module Background_thread : sig
(** Install this event loop in a background thread *) val setup_bg_thread : Nanoev.t -> unit
(** Install this event loop in a background thread *)
val has_bg_thread : unit -> bool val shutdown_bg_thread : unit -> unit
(** [has_bg_thread ()] is [true] iff a background thread is running a nanoev (** Shutdown background thread, assuming {! has_bg_thread} returns [true] *)
loop *)
val with_setup_bg_thread : Nanoev.t -> (unit -> 'a) -> 'a
val has_bg_thread : unit -> bool
(** [has_bg_thread ()] is [true] iff a background thread is running a nanoev
loop *)
end
(** {2 Non blocking IO primitives} *) (** {2 Non blocking IO primitives} *)
@ -33,4 +40,9 @@ val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr
@raise Nanoev.Closed if the FD is closed. @raise Nanoev.Closed if the FD is closed.
@raise Unix.Unix_error for other errors *) @raise Unix.Unix_error for other errors *)
val max_fds : unit -> int
(** Maximum number of file descriptors one can await on. See {!Nanoev.max_fds}
*)
val sleep : float -> unit val sleep : float -> unit
(** Suspend current fiber for [n] seconds *)