Skip to main content

windows_threading/
lib.rs

1#![doc = include_str!("../readme.md")]
2#![no_std]
3#![expect(non_snake_case, non_camel_case_types, clippy::upper_case_acronyms)]
4
5mod bindings;
6use bindings::*;
7
8mod pool;
9pub use pool::*;
10
11extern crate alloc;
12use alloc::boxed::Box;
13use core::ffi::c_void;
14use core::time::Duration;
15
16/// Submits a closure to the default thread pool.
17///
18/// The closure must be `Send + 'static`.
19///
20/// This uses `TrySubmitThreadpoolCallback` and reuses worker threads.
21pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
22    // SAFETY: the closure has `'static` lifetime.
23    assert!(
24        unsafe { submit_with_environment(core::ptr::null(), f) },
25        "allocation failed"
26    );
27}
28
29/// The order in which the thread pool runs queued callbacks.
30///
31/// Callbacks with a higher priority start before queued callbacks with a lower priority. Priority
32/// does not change the priority of the thread that runs the callback.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum Priority {
35    /// Runs before normal and low priority callbacks, such as for work the user is waiting on.
36    High,
37    /// The priority used by `submit`.
38    #[default]
39    Normal,
40    /// Runs after high and normal priority callbacks, such as for background indexing.
41    Low,
42}
43
44impl Priority {
45    fn to_raw(self) -> TP_CALLBACK_PRIORITY {
46        match self {
47            Self::High => TP_CALLBACK_PRIORITY_HIGH,
48            Self::Normal => TP_CALLBACK_PRIORITY_NORMAL,
49            Self::Low => TP_CALLBACK_PRIORITY_LOW,
50        }
51    }
52}
53
54/// Submits a closure to the default thread pool with the given priority.
55///
56/// The closure must be `Send + 'static`.
57pub fn submit_with_priority<F: FnOnce() + Send + 'static>(priority: Priority, f: F) {
58    let environment = environment(core::ptr::null_mut(), core::ptr::null_mut(), priority);
59
60    // SAFETY: the closure has `'static` lifetime, and the thread pool copies the environment.
61    assert!(
62        unsafe { submit_with_environment(&environment, f) },
63        "allocation failed"
64    );
65}
66
67/// Submits a closure to the default thread pool to run once `delay` has elapsed.
68///
69/// The closure must be `Send + 'static`. The delay is a minimum: the closure never runs before
70/// `delay` has elapsed, but it may run later if the system is busy or the system timer resolution
71/// is coarse, which is often about 15 milliseconds.
72pub fn submit_after<F: FnOnce() + Send + 'static>(delay: Duration, f: F) {
73    struct Delayed<F> {
74        deadline: Option<i64>,
75        f: F,
76    }
77
78    // Thread pool timers can expire before their due time, so the callback checks a monotonic
79    // deadline and rearms the one-shot timer until it has passed. The closure is only freed when
80    // it runs.
81    unsafe extern "system" fn callback<F: FnOnce() + Send>(
82        _: PTP_CALLBACK_INSTANCE,
83        context: *mut c_void,
84        timer: PTP_TIMER,
85    ) {
86        let delayed = context as *mut Delayed<F>;
87        let remaining = match unsafe { (*delayed).deadline } {
88            Some(deadline) => ticks_to_duration(deadline.saturating_sub(counter())),
89            None => Duration::MAX,
90        };
91
92        if remaining.is_zero() {
93            unsafe {
94                CloseThreadpoolTimer(timer);
95                (Box::from_raw(delayed).f)();
96            }
97        } else {
98            set_timer(timer, remaining);
99        }
100    }
101
102    let context = Box::into_raw(Box::new(Delayed {
103        deadline: duration_to_ticks(delay).and_then(|ticks| counter().checked_add(ticks)),
104        f,
105    }));
106    let timer =
107        unsafe { CreateThreadpoolTimer(Some(callback::<F>), context as _, core::ptr::null_mut()) };
108
109    if timer.is_null() {
110        // SAFETY: the thread pool did not take ownership of the closure.
111        drop(unsafe { Box::from_raw(context) });
112        panic!("allocation failed");
113    }
114
115    set_timer(timer, delay);
116}
117
118fn set_timer(timer: PTP_TIMER, delay: Duration) {
119    // A negative due time is relative to now, in 100-nanosecond units.
120    let ticks = delay.as_nanos().div_ceil(100).min(i64::MAX as u128) as i64;
121    let due = (-ticks) as u64;
122    let mut due = FILETIME {
123        dwLowDateTime: due as u32,
124        dwHighDateTime: (due >> 32) as u32,
125    };
126
127    unsafe { SetThreadpoolTimer(timer, &mut due, 0, 0) };
128}
129
130// The performance counter is the monotonic clock behind `std::time::Instant`.
131fn counter() -> i64 {
132    let mut value = LARGE_INTEGER::default();
133    unsafe {
134        QueryPerformanceCounter(&mut value);
135        value.QuadPart
136    }
137}
138
139fn frequency() -> u128 {
140    let mut value = LARGE_INTEGER::default();
141    unsafe {
142        QueryPerformanceFrequency(&mut value);
143        value.QuadPart as u128
144    }
145}
146
147// Both conversions round up so that a deadline is never reported as reached early.
148fn duration_to_ticks(duration: Duration) -> Option<i64> {
149    i64::try_from((duration.as_nanos() * frequency()).div_ceil(1_000_000_000)).ok()
150}
151
152fn ticks_to_duration(ticks: i64) -> Duration {
153    let nanos = (ticks.max(0) as u128 * 1_000_000_000).div_ceil(frequency());
154    Duration::from_nanos(nanos.min(u64::MAX as u128) as u64)
155}
156
157/// Calls the closure on each item in parallel and waits for completion.
158///
159/// The closure must be `Sync`, and iterator items must be `Send`.
160pub fn for_each<I, F, T>(i: I, f: F)
161where
162    I: Iterator<Item = T>,
163    F: Fn(T) + Sync,
164    T: Send,
165{
166    Pool::with_scope(|pool| {
167        for item in i {
168            pool.submit(|| f(item));
169        }
170    });
171}
172
173/// The thread identifier of the calling thread.
174pub fn thread_id() -> u32 {
175    unsafe { GetCurrentThreadId() }
176}
177
178/// Suspends the execution of the current thread until the time-out interval elapses.
179pub fn sleep(milliseconds: u32) {
180    unsafe {
181        Sleep(milliseconds);
182    }
183}
184
185// Thread-pool allocation failures are unrecoverable here.
186fn check<D: Default + PartialEq>(result: D) -> D {
187    assert!(result != D::default(), "allocation failed");
188
189    result
190}
191
192// As with `check`, but for the thread pool APIs that report failure by returning a null pointer.
193fn check_ptr<T>(result: *mut T) -> *mut T {
194    assert!(!result.is_null(), "allocation failed");
195
196    result
197}
198
199fn environment(
200    pool: PTP_POOL,
201    cleanup_group: PTP_CLEANUP_GROUP,
202    priority: Priority,
203) -> TP_CALLBACK_ENVIRON_V3 {
204    TP_CALLBACK_ENVIRON_V3 {
205        Version: 3,
206        Pool: pool,
207        CleanupGroup: cleanup_group,
208        CallbackPriority: priority.to_raw(),
209        Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
210        ..Default::default()
211    }
212}
213
214// This function is `unsafe` as it cannot ensure that the lifetime of the closure is sufficient or
215// whether the `environment` pointer is valid.
216unsafe fn submit_with_environment<F: FnOnce() + Send>(
217    environment: *const TP_CALLBACK_ENVIRON_V3,
218    f: F,
219) -> bool {
220    unsafe extern "system" fn callback<F: FnOnce() + Send>(
221        _: PTP_CALLBACK_INSTANCE,
222        callback: *mut c_void,
223    ) {
224        unsafe {
225            Box::from_raw(callback as *mut F)();
226        }
227    }
228
229    let context = Box::into_raw(Box::new(f));
230    if unsafe {
231        TrySubmitThreadpoolCallback(Some(callback::<F>), context as _, environment.cast_mut())
232    } != 0
233    {
234        true
235    } else {
236        // SAFETY: the thread pool rejected the callback and did not take ownership.
237        drop(unsafe { Box::from_raw(context) });
238        false
239    }
240}