Skip to main content

windows_threadpool_sys/
wait.rs

1// Copyright (c) 2026 Mike Grier
2//! Thread-pool waits: `CreateThreadpoolWait` / `SetThreadpoolWait` /
3//! `WaitForThreadpoolWaitCallbacks` / `CloseThreadpoolWait`.
4//!
5//! A wait object watches one waitable handle and queues its callback when the
6//! handle is signalled or the wait times out. Two SDK contracts shape this API:
7//!
8//! - **The handle must stay valid while a wait is pending.** [`ThreadpoolWait`]
9//!   therefore *owns* its handle rather than borrowing one, so it cannot be
10//!   closed underneath a pending wait. Use [`ThreadpoolWait::handle`] to signal
11//!   or inspect it.
12//! - **A wait fires at most once per arming.** The SDK requires the wait to be
13//!   rearmed explicitly for each activation, so the callback receives a
14//!   [`WaitActivation`] carrying [`WaitActivation::rearm`]. A callback that does
15//!   not rearm simply stops watching.
16//!
17//! Mutex handles are not supported by the thread pool and must not be passed to
18//! [`ThreadpoolWait::new`].
19
20use std::io;
21use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
22use std::ptr;
23use std::sync::Mutex;
24use std::sync::atomic::{AtomicIsize, Ordering};
25use std::time::Duration;
26
27use windows_sys::Win32::Foundation::{FALSE, FILETIME, HANDLE, TRUE, WAIT_TIMEOUT};
28use windows_sys::Win32::System::Threading::{
29    CloseThreadpoolWait, CreateEventW, CreateThreadpoolWait, PTP_CALLBACK_INSTANCE, PTP_WAIT,
30    SetThreadpoolWait, WaitForThreadpoolWaitCallbacks,
31};
32use windows_sys::core::BOOL;
33
34use crate::callback_env::CallbackEnviron;
35
36/// Wait results the pool reports. Changing either value is a breaking change.
37mod wait_status {
38    /// `WAIT_OBJECT_0`: the handle was signalled.
39    pub const SIGNALLED: u32 = 0;
40}
41
42/// 100-nanosecond intervals per second, for building a relative `FILETIME`.
43/// Changing this value is a breaking change.
44const FILETIME_TICKS_PER_SECOND: u64 = 10_000_000;
45/// Nanoseconds per 100-nanosecond interval. Changing it is a breaking change.
46const FILETIME_NANOS_PER_TICK: u32 = 100;
47
48/// Build the negative tick count that means "relative timeout".
49fn relative_filetime(timeout: Duration) -> FILETIME {
50    let ticks = timeout
51        .as_secs()
52        .saturating_mul(FILETIME_TICKS_PER_SECOND)
53        .saturating_add(u64::from(timeout.subsec_nanos() / FILETIME_NANOS_PER_TICK));
54    let ticks = i64::try_from(ticks).unwrap_or(i64::MAX);
55    let bits = (-ticks) as u64;
56    FILETIME {
57        dwLowDateTime: bits as u32,
58        dwHighDateTime: (bits >> 32) as u32,
59    }
60}
61
62/// A Win32 routine that closes a wait target.
63///
64/// This is the shape Win32 close routines already have, so one can be passed
65/// directly with no shim: `CloseHandle` and `FindCloseChangeNotification` both
66/// match it. The return value is ignored -- there is nothing a destructor could
67/// usefully do with a close failure.
68pub type WaitCloseFn = unsafe extern "system" fn(HANDLE) -> BOOL;
69
70/// Owns a handle that is closed with a routine other than `CloseHandle`.
71///
72/// The `Drop` lives here rather than on [`WaitTarget`] so that the enum itself
73/// has no destructor and can be taken apart by an ordinary `match`.
74pub(crate) struct CustomClose {
75    raw: HANDLE,
76    close: WaitCloseFn,
77}
78
79impl Drop for CustomClose {
80    fn drop(&mut self) {
81        // SAFETY: the handle was vouched for by `assume_waitable_with` and is
82        // still open -- every owner drains the wait before dropping this, so the
83        // pool is no longer watching it. This runs exactly once, because `Drop`
84        // does.
85        unsafe { (self.close)(self.raw) };
86    }
87}
88
89/// Owns a wait target and closes it with the routine that target requires.
90///
91/// Most handles are closed with `CloseHandle`, which is what a std
92/// [`OwnedHandle`] does, so that stays the default. Some are not: a
93/// `FindFirstChangeNotification` handle must be closed with
94/// `FindCloseChangeNotification`, and closing it the usual way is wrong. The
95/// second variant carries the caller's routine so those targets can be owned by
96/// the pool on the same terms as any other.
97pub(crate) enum WaitTarget {
98    /// The default: closed by [`OwnedHandle`]'s own drop, with `CloseHandle`.
99    Owned(OwnedHandle),
100    /// Closed with the caller-supplied routine.
101    Custom(CustomClose),
102}
103
104// SAFETY: a handle is an opaque OS-owned value, not a pointer into this
105// process, and both variants only ever read it or hand it to a thread-safe Win32
106// call. This restores what the plain `OwnedHandle` field had automatically.
107unsafe impl Send for WaitTarget {}
108unsafe impl Sync for WaitTarget {}
109
110impl WaitTarget {
111    /// The raw handle, for arming the wait and for the callback context.
112    pub(crate) fn raw(&self) -> HANDLE {
113        match self {
114            WaitTarget::Owned(handle) => handle.as_raw_handle(),
115            WaitTarget::Custom(custom) => custom.raw,
116        }
117    }
118
119    /// Borrow the handle, for signalling or inspecting it.
120    pub(crate) fn borrow(&self) -> BorrowedHandle<'_> {
121        match self {
122            WaitTarget::Owned(handle) => handle.as_handle(),
123            // SAFETY: the handle stays open for as long as `self` owns it, and
124            // the returned borrow cannot outlive that.
125            WaitTarget::Custom(custom) => unsafe { BorrowedHandle::borrow_raw(custom.raw) },
126        }
127    }
128}
129
130impl std::fmt::Debug for WaitTarget {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        // The close routine is a code pointer with no useful rendering.
133        f.debug_struct("WaitTarget")
134            .field("raw", &self.raw())
135            .field(
136                "close",
137                &match self {
138                    WaitTarget::Owned(_) => "CloseHandle",
139                    WaitTarget::Custom(_) => "custom",
140                },
141            )
142            .finish()
143    }
144}
145
146/// A handle the thread pool is able to wait on.
147///
148/// The pool does not support every waitable object: a mutex handle in
149/// particular produces undefined behaviour rather than an error. Requiring this
150/// type instead of a bare [`OwnedHandle`] moves that precondition from prose
151/// into the type system, so a safe caller cannot reach the undefined case.
152///
153/// Construct one safely with [`WaitableHandle::event`], or vouch for a handle
154/// obtained elsewhere with the narrow [`WaitableHandle::assume_waitable`] seam --
155/// or [`WaitableHandle::assume_waitable_with`] when the handle needs a close
156/// routine other than `CloseHandle`.
157/// This mirrors `UnassociatedEndpoint` in `windows-overlapped-io-sys`, which
158/// pairs a safe `open` with an `assume_overlapped` escape hatch for the same
159/// reason.
160#[derive(Debug)]
161pub struct WaitableHandle {
162    target: WaitTarget,
163}
164
165impl WaitableHandle {
166    /// Create an event and wrap it as a waitable handle.
167    ///
168    /// An event is always a supported wait target, so this needs no `unsafe`.
169    /// A `manual_reset` event stays signalled until it is reset; an auto-reset
170    /// event returns to unsignalled as soon as one wait is satisfied, which
171    /// makes it the usual choice for handing off work one activation at a time.
172    ///
173    /// # Errors
174    ///
175    /// Returns the error from `CreateEventW`.
176    pub fn event(manual_reset: bool, initially_signalled: bool) -> io::Result<Self> {
177        // SAFETY: creating an unnamed event with default security attributes;
178        // all pointer arguments are null by design.
179        let raw = unsafe {
180            CreateEventW(
181                ptr::null(),
182                if manual_reset { TRUE } else { FALSE },
183                if initially_signalled { TRUE } else { FALSE },
184                ptr::null(),
185            )
186        };
187        if raw.is_null() {
188            return Err(io::Error::last_os_error());
189        }
190        // SAFETY: the call returned a fresh, exclusively owned event handle.
191        Ok(Self {
192            target: WaitTarget::Owned(unsafe { OwnedHandle::from_raw_handle(raw) }),
193        })
194    }
195
196    /// Wrap a handle whose wait support the caller vouches for.
197    ///
198    /// This is the extensibility seam for wait targets this crate cannot create
199    /// itself -- semaphores, waitable timers, processes, threads, console input,
200    /// change notifications, and so on.
201    ///
202    /// # Safety
203    ///
204    /// The caller guarantees that:
205    ///
206    /// - the handle is a waitable object the thread pool supports, and in
207    ///   particular is **not a mutex**, which the SDK does not support and which
208    ///   yields undefined behaviour rather than an error; and
209    /// - ownership transfers exclusively into the returned value, so nothing
210    ///   else closes the handle while a wait on it is pending.
211    #[must_use]
212    pub unsafe fn assume_waitable(handle: OwnedHandle) -> Self {
213        Self {
214            target: WaitTarget::Owned(handle),
215        }
216    }
217
218    /// Wrap a handle that must be closed with a routine other than
219    /// `CloseHandle`.
220    ///
221    /// Some waitable objects have their own destructor: a
222    /// `FindFirstChangeNotification` handle is closed with
223    /// `FindCloseChangeNotification`, and handing it to
224    /// [`assume_waitable`](Self::assume_waitable) --
225    /// which takes a std [`OwnedHandle`] and therefore closes it with
226    /// `CloseHandle` -- would be wrong. `close` is invoked exactly once, and
227    /// only after the wait has been drained, whether the object is torn down by
228    /// [`ThreadpoolWait`]'s own drop or by a
229    /// [`CleanupGroup`](crate::cleanup_group::CleanupGroup) release.
230    ///
231    /// `close` has the shape Win32 close routines already have, so it can be
232    /// passed directly with no wrapper.
233    ///
234    /// # Safety
235    ///
236    /// The caller guarantees that:
237    ///
238    /// - the handle is a waitable object the thread pool supports, and in
239    ///   particular is **not a mutex**, which the SDK does not support and which
240    ///   yields undefined behaviour rather than an error;
241    /// - ownership transfers exclusively into the returned value, so nothing
242    ///   else closes the handle while a wait on it is pending; and
243    /// - `close` is the correct destructor for this handle and is safe to call
244    ///   once on it after the pool has stopped watching it.
245    #[must_use]
246    pub unsafe fn assume_waitable_with(handle: HANDLE, close: WaitCloseFn) -> Self {
247        Self {
248            target: WaitTarget::Custom(CustomClose { raw: handle, close }),
249        }
250    }
251
252    /// Borrow the underlying handle, for signalling or inspecting it.
253    #[must_use]
254    pub fn handle(&self) -> BorrowedHandle<'_> {
255        self.target.borrow()
256    }
257
258    /// Consume the wrapper and recover the owned handle.
259    ///
260    /// # Errors
261    ///
262    /// Returns the wrapper back unchanged when it carries a custom close
263    /// routine (see [`assume_waitable_with`](Self::assume_waitable_with)): an
264    /// [`OwnedHandle`] closes what it holds with `CloseHandle`, which is
265    /// precisely the wrong destructor for such a target, so there is no correct
266    /// value to hand back. The handle is neither closed nor leaked -- ownership
267    /// simply stays where it was.
268    pub fn into_handle(self) -> Result<OwnedHandle, Self> {
269        match self.target {
270            WaitTarget::Owned(handle) => Ok(handle),
271            target @ WaitTarget::Custom(_) => Err(Self { target }),
272        }
273    }
274
275    /// Consume the wrapper and recover the owner, whichever kind it is.
276    pub(crate) fn into_target(self) -> WaitTarget {
277        self.target
278    }
279}
280
281/// Why a wait callback ran.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum WaitResult {
284    /// The watched handle became signalled.
285    Signalled,
286    /// The timeout given when the wait was armed elapsed first.
287    TimedOut,
288    /// The pool reported a result this crate does not model. The raw value is
289    /// preserved so a caller can inspect it rather than having it discarded.
290    Other(u32),
291}
292
293impl WaitResult {
294    fn from_raw(value: u32) -> Self {
295        match value {
296            wait_status::SIGNALLED => Self::Signalled,
297            WAIT_TIMEOUT => Self::TimedOut,
298            other => Self::Other(other),
299        }
300    }
301}
302
303/// Heap-allocated callback state kept alive for the lifetime of the wait object.
304///
305/// `wait` is filled in after `CreateThreadpoolWait` returns, because rearming
306/// from inside a callback needs the object the callback belongs to.
307struct WaitContext {
308    wait: AtomicIsize,
309    handle: HANDLE,
310    /// How many callers are currently suppressing re-arming: zero means allowed.
311    ///
312    /// Arming takes this lock and does nothing while the count is non-zero, so a
313    /// callback that re-arms cannot start watching again after a disarm from
314    /// outside: without it, a drain could complete with the object armed again,
315    /// and for `Drop` that meant closing the object and freeing its context with
316    /// a fresh callback queued against them.
317    ///
318    /// A count rather than a flag because suppression has two users with
319    /// different lifetimes: [`ThreadpoolWait::stop_and_drain`] raises it and
320    /// lowers it again, while `Drop` raises it permanently. With a flag, a
321    /// `stop_and_drain` finishing would clear a suppression that another
322    /// concurrent one still needed.
323    ///
324    /// The lock is only ever held across the native `SetThreadpoolWait` call,
325    /// never across a callback drain, which would deadlock a callback that
326    /// happened to be blocked on it.
327    suppress_rearm: Mutex<u32>,
328    callback: Box<dyn Fn(&WaitActivation<'_>) + Send + Sync + 'static>,
329}
330
331impl WaitContext {
332    /// Lock the suppression count, recovering from a panicking holder.
333    fn suppression(&self) -> std::sync::MutexGuard<'_, u32> {
334        self.suppress_rearm
335            .lock()
336            .unwrap_or_else(|poison| poison.into_inner())
337    }
338
339    /// Start suppressing re-arming, and disarm under the same acquisition.
340    ///
341    /// Doing both under one lock is what makes the pair atomic against a
342    /// callback: a re-arm either lands entirely before this, or is suppressed by
343    /// it. The lock is released before any drain.
344    fn suppress_and_disarm(&self) {
345        let mut suppressed = self.suppression();
346        *suppressed = suppressed.saturating_add(1);
347        let wait = self.wait.load(Ordering::Acquire);
348        if wait != 0 {
349            // SAFETY: `wait` is this object's live PTP_WAIT, published before any
350            // callback could run and valid until Drop closes it.
351            unsafe { disarm_raw(wait) };
352        }
353    }
354
355    /// Stop suppressing re-arming.
356    fn release_suppression(&self) {
357        let mut suppressed = self.suppression();
358        *suppressed = suppressed.saturating_sub(1);
359    }
360}
361
362// SAFETY: `handle` is a raw handle owned by the ThreadpoolWait that outlives
363// this context; it is only passed back to SetThreadpoolWait, never closed here.
364unsafe impl Send for WaitContext {}
365unsafe impl Sync for WaitContext {}
366
367/// One activation of a [`ThreadpoolWait`], handed to its callback.
368///
369/// The wait is not armed when the callback runs. Call [`WaitActivation::rearm`]
370/// to watch the handle again; doing nothing leaves the wait idle.
371pub struct WaitActivation<'ctx> {
372    result: WaitResult,
373    ctx: &'ctx WaitContext,
374}
375
376impl std::fmt::Debug for WaitActivation<'_> {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        // The context holds the boxed callback and the raw wait object, neither
379        // of which is meaningful to a reader; the result is the whole story.
380        f.debug_struct("WaitActivation")
381            .field("result", &self.result)
382            .finish_non_exhaustive()
383    }
384}
385
386impl WaitActivation<'_> {
387    /// Why this callback ran.
388    #[must_use]
389    pub fn result(&self) -> WaitResult {
390        self.result
391    }
392
393    /// Whether the watched handle was signalled.
394    #[must_use]
395    pub fn is_signalled(&self) -> bool {
396        self.result == WaitResult::Signalled
397    }
398
399    /// Borrow the handle this activation was for.
400    ///
401    /// The wait owns the handle and outlives every callback, so it is open for
402    /// the duration of this borrow. This is what makes the documented way out of
403    /// the overlap hazard on [`rearm`](Self::rearm) reachable: a callback
404    /// watching a manual-reset event can reset it before re-arming, so the next
405    /// activation waits for a fresh signal instead of starting immediately
406    /// alongside this one.
407    #[must_use]
408    pub fn handle(&self) -> BorrowedHandle<'_> {
409        // SAFETY: the wait owns this handle and cannot be dropped while a
410        // callback is running, so it is open for at least this borrow.
411        unsafe { BorrowedHandle::borrow_raw(self.ctx.handle) }
412    }
413
414    /// Arm the wait again, so the next signal or timeout activates it.
415    ///
416    /// `timeout` of `None` waits indefinitely. This is the mechanism the SDK
417    /// requires for repeated waits: an activation consumes the arming, so a
418    /// callback that wants to keep watching must rearm from inside itself.
419    ///
420    /// # This can overlap the callback with itself
421    ///
422    /// Re-arming takes effect immediately, and the pool activates as soon as the
423    /// handle is signalled. If the handle is *still signalled* when this is
424    /// called -- which is the normal state of a manual-reset event -- the next
425    /// activation is queued at once and can begin before the current callback
426    /// returns. Re-arming early in a long callback therefore runs it
427    /// concurrently with itself, repeatedly: a 20ms callback that re-armed at
428    /// its start was measured entering 7529 times in 400ms, 5110 of those
429    /// overlapping an earlier entry.
430    ///
431    /// This is not the guarantee [`TimerFiring::rearm_after`] gives. A one-shot
432    /// timer's re-arm is deferred until the callback returns, precisely so
433    /// firings stay sequential; a wait's re-arm is not, because the SDK requires
434    /// the wait to be re-armed for the handle's *current* signal state to be
435    /// observed.
436    ///
437    /// Either reset the handle before re-arming, using
438    /// [`handle`](Self::handle), so the next activation waits for a fresh
439    /// signal:
440    ///
441    /// ```no_run
442    /// # use std::os::windows::io::AsRawHandle;
443    /// # use windows_sys::Win32::System::Threading::ResetEvent;
444    /// # fn example(activation: &windows_threadpool_sys::wait::WaitActivation<'_>) {
445    /// // SAFETY: the wait owns the event, so the handle is open here.
446    /// unsafe { ResetEvent(activation.handle().as_raw_handle()) };
447    /// activation.rearm(None);
448    /// # }
449    /// ```
450    ///
451    /// or accept the concurrency and make everything the callback touches
452    /// tolerate it. An auto-reset event does not have this problem, because the
453    /// wait consumes the signal.
454    ///
455    /// [`TimerFiring::rearm_after`]: crate::timer::TimerFiring::rearm_after
456    ///
457    /// # Teardown
458    ///
459    /// Re-arming after the object has begun tearing down does nothing, so a
460    /// callback racing [`ThreadpoolWait`]'s `Drop` cannot leave the object armed
461    /// behind it.
462    pub fn rearm(&self, timeout: Option<Duration>) {
463        let _ = self.rearm_reporting(timeout);
464    }
465
466    /// [`rearm`](Self::rearm), reporting whether the arming actually happened.
467    ///
468    /// Returns `false` when the request was suppressed because the object is
469    /// tearing down. The public entry point discards this, because a caller
470    /// cannot act on it: by the time it could look, the object is gone. Tests
471    /// use it to observe the suppression directly, which is otherwise only
472    /// visible as the absence of undefined behaviour.
473    pub(crate) fn rearm_reporting(&self, timeout: Option<Duration>) -> bool {
474        // Taken before arming and held across it, so this either happens before
475        // a suppressing caller raises the count or is suppressed by it -- never
476        // in between.
477        let suppressed = self.ctx.suppression();
478        if *suppressed > 0 {
479            return false;
480        }
481        let wait = self.ctx.wait.load(Ordering::Acquire);
482        debug_assert_ne!(
483            wait, 0,
484            "the wait object must be published before callbacks"
485        );
486        // SAFETY: `wait` is this object's live PTP_WAIT, published before any
487        // callback could run, and `handle` is owned by that object so it is
488        // still open. The timeout, if any, is a live stack value for the call.
489        unsafe { arm_raw(wait, self.ctx.handle, timeout) };
490        drop(suppressed);
491        true
492    }
493}
494
495/// Stop a raw wait object.
496///
497/// SAFETY: `wait` must be a live `PTP_WAIT`.
498pub(crate) unsafe fn disarm_raw(wait: PTP_WAIT) {
499    // SAFETY: forwarded; a null handle is the documented way to cancel a wait.
500    unsafe { SetThreadpoolWait(wait, ptr::null_mut(), ptr::null()) };
501}
502
503/// Arm a raw wait object against a borrowed target.
504///
505/// SAFETY: `wait` must be a live `PTP_WAIT` and `target` must stay open until
506/// the wait is disarmed or the object released.
507pub(crate) unsafe fn arm_member(wait: PTP_WAIT, target: &WaitTarget, timeout: Option<Duration>) {
508    // SAFETY: forwarded from this function's own contract.
509    unsafe { arm_raw(wait, target.raw(), timeout) };
510}
511
512/// Arm or disarm a wait object.
513///
514/// SAFETY: `wait` must be a live `PTP_WAIT` and `handle` a live waitable handle
515/// (or null to disarm).
516unsafe fn arm_raw(wait: PTP_WAIT, handle: HANDLE, timeout: Option<Duration>) {
517    match timeout {
518        Some(timeout) => {
519            let filetime = relative_filetime(timeout);
520            // SAFETY: forwarded from this function's contract; `filetime` is
521            // read only for the duration of the call.
522            unsafe { SetThreadpoolWait(wait, handle, &filetime) };
523        }
524        // SAFETY: forwarded; a null timeout means "wait indefinitely".
525        None => unsafe { SetThreadpoolWait(wait, handle, ptr::null()) },
526    }
527}
528
529/// Trampoline from the raw `PTP_WAIT_CALLBACK` ABI into the boxed closure.
530///
531/// SAFETY: `context` must point to a live [`WaitContext`] for the entire
532/// duration of every callback invocation, which [`ThreadpoolWait`]'s `Drop`
533/// ordering guarantees.
534unsafe extern "system" fn wait_trampoline(
535    _instance: PTP_CALLBACK_INSTANCE,
536    context: *mut core::ffi::c_void,
537    _wait: PTP_WAIT,
538    wait_result: u32,
539) {
540    // SAFETY: context is a valid *mut WaitContext for the full callback duration.
541    let ctx = unsafe { &*(context as *const WaitContext) };
542    let activation = WaitActivation {
543        result: WaitResult::from_raw(wait_result),
544        ctx,
545    };
546    // Not contained: see the callback contract in the crate docs.
547    (ctx.callback)(&activation);
548}
549
550/// An owned thread-pool wait object bound to one waitable handle.
551///
552/// The object owns the handle, so the handle cannot be closed while a wait is
553/// pending. A newly created wait is idle; arm it with [`ThreadpoolWait::arm`],
554/// and rearm from inside the callback with [`WaitActivation::rearm`].
555///
556/// [`Drop`] disarms before draining callbacks, then closes the object and only
557/// afterwards releases the callback context and the handle.
558///
559/// Unlike [`ThreadpoolTimer`](crate::timer::ThreadpoolTimer), **the callback can
560/// run concurrently with itself**: a wait's re-arm takes effect immediately, so
561/// re-arming while the handle is still signalled queues the next activation
562/// before the current callback returns. See [`WaitActivation::rearm`] for the
563/// measurements and the two ways to avoid it.
564///
565/// # Examples
566///
567/// Watch an event once. The wait takes ownership of the handle, and
568/// [`ThreadpoolWait::handle`] borrows it back for signalling:
569///
570/// ```
571/// use std::os::windows::io::AsRawHandle;
572/// use std::sync::mpsc;
573/// use windows_sys::Win32::System::Threading::SetEvent;
574/// use windows_threadpool_sys::wait::{ThreadpoolWait, WaitResult, WaitableHandle};
575///
576/// let event = WaitableHandle::event(true, false)?;
577///
578/// let (tx, rx) = mpsc::channel();
579/// let sender = std::sync::Mutex::new(tx);
580/// let wait = ThreadpoolWait::new(event, move |activation| {
581///     let _ = sender.lock().expect("send").send(activation.result());
582/// }, None)?;
583///
584/// wait.arm(None);
585/// // SAFETY: the wait owns the event, so the handle is still open.
586/// unsafe { SetEvent(wait.handle().as_raw_handle()) };
587///
588/// assert_eq!(rx.recv().expect("activation"), WaitResult::Signalled);
589/// # Ok::<(), std::io::Error>(())
590/// ```
591///
592/// Keep watching across activations by rearming from inside the callback, which
593/// is what the SDK requires -- an activation consumes the arming:
594///
595/// ```
596/// # use std::os::windows::io::AsRawHandle;
597/// # use std::sync::Arc;
598/// # use std::sync::atomic::{AtomicUsize, Ordering};
599/// # use windows_sys::Win32::System::Threading::SetEvent;
600/// use windows_threadpool_sys::wait::{ThreadpoolWait, WaitableHandle};
601///
602/// let event = WaitableHandle::event(false, false)?;
603///
604/// let seen = Arc::new(AtomicUsize::new(0));
605/// let counter = Arc::clone(&seen);
606/// let wait = ThreadpoolWait::new(event, move |activation| {
607///     counter.fetch_add(1, Ordering::SeqCst);
608///     activation.rearm(None);
609/// }, None)?;
610///
611/// wait.arm(None);
612/// for _ in 0..3 {
613///     // SAFETY: the wait owns the event, so the handle is still open.
614///     unsafe { SetEvent(wait.handle().as_raw_handle()) };
615///     std::thread::sleep(std::time::Duration::from_millis(5));
616/// }
617///
618/// wait.disarm();
619/// wait.wait();
620/// assert!(seen.load(Ordering::SeqCst) >= 1);
621/// # Ok::<(), std::io::Error>(())
622/// ```
623pub struct ThreadpoolWait {
624    wait: PTP_WAIT,
625    target: WaitTarget,
626    // Kept alive as a raw pointer until Drop has disarmed and drained.
627    context: *mut WaitContext,
628}
629
630// SAFETY: PTP_WAIT is a cross-thread pool object, WaitTarget is Send + Sync,
631// and the context is Send + Sync; the pointer is only read until Drop frees it
632// after all callbacks have finished.
633unsafe impl Send for ThreadpoolWait {}
634unsafe impl Sync for ThreadpoolWait {}
635
636impl ThreadpoolWait {
637    /// Create an idle wait watching `handle`.
638    ///
639    /// The object takes ownership of the handle and closes it on drop, which is
640    /// what guarantees the handle outlives any pending wait.
641    ///
642    /// Pass `Some(env)` to select a private pool or callback priority; `None`
643    /// uses the process-default pool with default priority.
644    ///
645    /// The callback runs on a shared, process-managed pool thread, must restore
646    /// any thread state it changes, and must not terminate its thread. It must
647    /// not panic: a panic unwinds to the `extern "system"` trampoline and aborts
648    /// the process.
649    ///
650    /// Taking a [`WaitableHandle`] rather than a bare handle is what keeps this
651    /// constructor safe: the thread pool does not support every waitable object,
652    /// and a mutex handle in particular is undefined rather than an error.
653    ///
654    /// # Errors
655    ///
656    /// Returns the error from `CreateThreadpoolWait`.
657    pub fn new<F>(
658        handle: WaitableHandle,
659        callback: F,
660        env: Option<&mut CallbackEnviron<'_>>,
661    ) -> io::Result<Self>
662    where
663        F: Fn(&WaitActivation<'_>) + Send + Sync + 'static,
664    {
665        let target = handle.into_target();
666        let context = Box::into_raw(Box::new(WaitContext {
667            wait: AtomicIsize::new(0),
668            handle: target.raw(),
669            suppress_rearm: Mutex::new(0),
670            callback: Box::new(callback),
671        }));
672        let env_ptr = env.map_or(ptr::null_mut(), |e| e.as_mut_ptr());
673
674        // SAFETY: context is a valid heap pointer that outlives every callback,
675        // and env_ptr is valid (or null) for the duration of this call.
676        let wait = unsafe {
677            CreateThreadpoolWait(Some(wait_trampoline), context.cast(), env_ptr.cast_const())
678        };
679
680        if wait == 0 {
681            let error = io::Error::last_os_error();
682            // SAFETY: the pool never saw context; reclaim it immediately.
683            unsafe { drop(Box::from_raw(context)) };
684            return Err(error);
685        }
686
687        // Publish the object before any callback can run. No wait is armed yet,
688        // so no callback can observe the unpublished value.
689        // SAFETY: context is live and exclusively ours until the first arming.
690        unsafe { (*context).wait.store(wait, Ordering::Release) };
691
692        Ok(Self {
693            wait,
694            target,
695            context,
696        })
697    }
698
699    /// Borrow the watched handle, for signalling or inspecting it.
700    #[must_use]
701    pub fn handle(&self) -> BorrowedHandle<'_> {
702        self.target.borrow()
703    }
704
705    /// Arm the wait, so the next signal or timeout runs the callback once.
706    ///
707    /// `timeout` of `None` waits indefinitely. Arming replaces any previous
708    /// arming rather than adding to it, and an activation consumes the arming --
709    /// rearm from inside the callback with [`WaitActivation::rearm`] to keep
710    /// watching.
711    pub fn arm(&self, timeout: Option<Duration>) {
712        // SAFETY: `wait` is valid for the lifetime of self, and the handle is
713        // owned by self so it is still open.
714        unsafe { arm_raw(self.wait, self.target.raw(), timeout) };
715    }
716
717    /// Stop watching.
718    ///
719    /// New activations stop being queued, but a callback already queued still
720    /// runs; use [`ThreadpoolWait::cancel_pending`] to drop those as well.
721    pub fn disarm(&self) {
722        // SAFETY: `wait` is valid for the lifetime of self; a null handle is the
723        // documented way to cancel a pending wait.
724        unsafe { SetThreadpoolWait(self.wait, ptr::null_mut(), ptr::null()) };
725    }
726
727    /// Let every queued callback run, and block until none is executing.
728    ///
729    /// This does **not** leave a self-re-arming wait idle: a callback running
730    /// during this call can [`rearm`](WaitActivation::rearm) before it returns,
731    /// so the object is watching again when this returns. Use
732    /// [`stop_and_drain`](Self::stop_and_drain) to reach quiescence.
733    pub fn wait(&self) {
734        // SAFETY: `wait` is valid for the lifetime of self.
735        unsafe { WaitForThreadpoolWaitCallbacks(self.wait, FALSE) };
736    }
737
738    /// Drop callbacks that have not started, then wait for any executing one.
739    ///
740    /// Like [`wait`](Self::wait), this does not by itself leave a self-re-arming
741    /// wait idle: it does not suppress the re-arm of a callback that is already
742    /// running. Use [`stop_and_drain`](Self::stop_and_drain) when the wait must
743    /// actually be quiescent afterwards.
744    pub fn cancel_pending(&self) {
745        // SAFETY: `wait` is valid for the lifetime of self. A cancelled wait
746        // callback owns no storage, so dropping queued callbacks orphans nothing.
747        unsafe { WaitForThreadpoolWaitCallbacks(self.wait, TRUE) };
748    }
749
750    /// Stop watching and block until the wait is idle, leaving it reusable.
751    ///
752    /// This exists because neither [`disarm`](Self::disarm) nor
753    /// [`cancel_pending`](Self::cancel_pending) can stop a self-re-arming wait on
754    /// its own: a callback already running can call [`WaitActivation::rearm`]
755    /// after a disarm from outside has taken effect. This suppresses re-arming
756    /// for the duration of the call, using the same mechanism `Drop` uses, and
757    /// lifts the suppression before returning so the wait can be armed again.
758    ///
759    /// # What this guarantees
760    ///
761    /// On return, provided no other thread arms the wait during the call:
762    ///
763    /// - no callback is queued or executing, and
764    /// - the object is not watching -- a re-arm requested by a callback that ran
765    ///   during the call is discarded rather than deferred.
766    ///
767    /// # What it does not
768    ///
769    /// **A concurrent [`arm`](Self::arm) from another thread is not excluded.**
770    /// `ThreadpoolWait` is `Sync` and `arm` takes `&self`, so it does not pass
771    /// through the suppression this uses, and nothing in this crate orders such
772    /// a call against this one. A caller needing the wait to be provably idle
773    /// must ensure nothing else arms it for the duration, by owning it
774    /// exclusively or serializing access to it.
775    ///
776    /// Calling this from inside the wait's own callback would deadlock, because
777    /// it waits for that callback to finish.
778    pub fn stop_and_drain(&self) {
779        // SAFETY: the context outlives every callback and is freed only by Drop,
780        // which cannot run while this borrow of self is alive.
781        let ctx = unsafe { &*self.context };
782        ctx.suppress_and_disarm();
783        // Drained with the lock released: a callback blocked on it would
784        // otherwise never finish, and this would never return.
785        self.cancel_pending();
786        ctx.release_suppression();
787    }
788
789    /// Give up ownership, returning the raw object, its callback context, and
790    /// the watched target.
791    ///
792    /// Used only by [`crate::cleanup_group::CleanupGroup`], which takes over all
793    /// three. The target must go with them: the pool may still be watching it
794    /// until the group releases the member, so it cannot be closed when the
795    /// borrowing member goes out of scope.
796    pub(crate) fn into_parts(self) -> (PTP_WAIT, *mut core::ffi::c_void, WaitTarget) {
797        let this = std::mem::ManuallyDrop::new(self);
798        // SAFETY: `this` is never dropped, so moving the target out cannot be
799        // observed by a later drop of the original value.
800        let target = unsafe { ptr::read(&this.target) };
801        (this.wait, this.context.cast(), target)
802    }
803
804    /// Free a context returned by [`ThreadpoolWait::into_parts`].
805    ///
806    /// # Safety
807    ///
808    /// `context` must come from `into_parts` on this type, its object must
809    /// already have been released, and it must be freed exactly once.
810    pub(crate) unsafe fn drop_context(context: *mut core::ffi::c_void) {
811        // SAFETY: forwarded from this function's own contract.
812        drop(unsafe { Box::from_raw(context.cast::<WaitContext>()) });
813    }
814
815    /// Suppress this member's re-arm and disarm it, before a
816    /// [`crate::cleanup_group::CleanupGroup`] bulk-releases its members.
817    ///
818    /// `CloseThreadpoolCleanupGroupMembers` waits for executing callbacks but
819    /// does not stop one from re-arming: a callback still running can call
820    /// [`WaitActivation::rearm`] after the bulk release has begun, which would
821    /// re-arm an object being torn down and then free its context under a freshly
822    /// queued callback. Raising the suppression before the release closes that
823    /// door, exactly as this type's own `Drop` does; the suppression is never
824    /// lifted because the member is being destroyed.
825    ///
826    /// # Safety
827    ///
828    /// `context` must come from [`into_parts`](Self::into_parts) on this type
829    /// and name a still-live object whose context the caller has not yet freed.
830    pub(crate) unsafe fn prepare_shutdown(context: *mut core::ffi::c_void) {
831        // SAFETY: forwarded; the context outlives the member until the group
832        // frees it, and `suppress_and_disarm` only touches this object.
833        let ctx = unsafe { &*context.cast::<WaitContext>() };
834        ctx.suppress_and_disarm();
835    }
836}
837
838impl Drop for ThreadpoolWait {
839    fn drop(&mut self) {
840        // Close the door on re-arming before disarming, and do both under the
841        // same lock. Disarming alone is not enough: a callback already running
842        // could re-arm afterwards, the drain below could then return with the
843        // object armed, and the close and context free would race a freshly
844        // queued callback.
845        // SAFETY: the context outlives every callback; Drop frees it below,
846        // after the drain.
847        let ctx = unsafe { &*self.context };
848        // Raised and never released: unlike `stop_and_drain`, there is no
849        // afterwards for this object.
850        ctx.suppress_and_disarm();
851        // The lock is released before draining: a callback blocked on it would
852        // otherwise never finish, and this wait would never return.
853        self.cancel_pending();
854
855        // SAFETY: no callback can be queued or executing, so the object can be
856        // closed and the context freed exactly once. `target` is dropped after
857        // this, when its field is dropped, so the handle outlives the wait
858        // object and its close routine -- `CloseHandle` or a custom one -- runs
859        // only once the pool has stopped watching it.
860        unsafe {
861            CloseThreadpoolWait(self.wait);
862            drop(Box::from_raw(self.context));
863        }
864    }
865}
866
867#[cfg(test)]
868mod tests;