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;
14
15/// Submits a closure to the default thread pool.
16///
17/// The closure must be `Send + 'static`.
18///
19/// This uses `TrySubmitThreadpoolCallback` and reuses worker threads.
20pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
21    // SAFETY: the closure has `'static` lifetime.
22    assert!(
23        unsafe { submit_with_environment(core::ptr::null(), f) },
24        "allocation failed"
25    );
26}
27
28/// Calls the closure on each item in parallel and waits for completion.
29///
30/// The closure must be `Sync`, and iterator items must be `Send`.
31pub fn for_each<I, F, T>(i: I, f: F)
32where
33    I: Iterator<Item = T>,
34    F: Fn(T) + Sync,
35    T: Send,
36{
37    Pool::with_scope(|pool| {
38        for item in i {
39            pool.submit(|| f(item));
40        }
41    });
42}
43
44/// The thread identifier of the calling thread.
45pub fn thread_id() -> u32 {
46    unsafe { GetCurrentThreadId() }
47}
48
49/// Suspends the execution of the current thread until the time-out interval elapses.
50pub fn sleep(milliseconds: u32) {
51    unsafe {
52        Sleep(milliseconds);
53    }
54}
55
56// Thread-pool allocation failures are unrecoverable here.
57fn check<D: Default + PartialEq>(result: D) -> D {
58    assert!(result != D::default(), "allocation failed");
59
60    result
61}
62
63// As with `check`, but for the thread pool APIs that report failure by returning a null pointer.
64fn check_ptr<T>(result: *mut T) -> *mut T {
65    assert!(!result.is_null(), "allocation failed");
66
67    result
68}
69
70// This function is `unsafe` as it cannot ensure that the lifetime of the closure is sufficient or
71// whether the `environment` pointer is valid.
72unsafe fn submit_with_environment<F: FnOnce() + Send>(
73    environment: *const TP_CALLBACK_ENVIRON_V3,
74    f: F,
75) -> bool {
76    unsafe extern "system" fn callback<F: FnOnce() + Send>(
77        _: *mut TP_CALLBACK_INSTANCE,
78        callback: *mut c_void,
79    ) {
80        unsafe {
81            Box::from_raw(callback as *mut F)();
82        }
83    }
84
85    let context = Box::into_raw(Box::new(f));
86    if unsafe { TrySubmitThreadpoolCallback(Some(callback::<F>), context as _, environment) } != 0 {
87        true
88    } else {
89        // SAFETY: the thread pool rejected the callback and did not take ownership.
90        drop(unsafe { Box::from_raw(context) });
91        false
92    }
93}