Skip to main content

windows_threading/
pool.rs

1use super::*;
2use core::{marker::PhantomData, ops::Deref};
3
4/// A `Pool` object represents a private thread pool with its own thread limits.
5///
6/// This is in contrast to the default, or shared, thread pool used by the crate's `submit` function
7/// as well as other code within the same process.
8pub struct Pool(Box<TP_CALLBACK_ENVIRON_V3>);
9
10impl Pool {
11    /// Creates a new `Pool` object.
12    pub fn new() -> Self {
13        let mut e = TP_CALLBACK_ENVIRON_V3 {
14            Version: 3,
15            CallbackPriority: TP_CALLBACK_PRIORITY_NORMAL,
16            Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
17            ..Default::default()
18        };
19
20        unsafe {
21            e.Pool = check_ptr(CreateThreadpool(core::ptr::null()));
22            e.CleanupGroup = check_ptr(CreateThreadpoolCleanupGroup());
23        }
24
25        // Box the environment so its address remains stable for the lifetime of the `Pool`.
26        Self(Box::new(e))
27    }
28
29    /// Convenience function for creating a new pool and calling [`scope`][Self::scope].
30    pub fn with_scope<'env, F>(f: F)
31    where
32        F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>),
33    {
34        let pool = Self::new();
35        pool.scope(f);
36    }
37
38    /// Sets the thread limits for the `Pool` object.
39    pub fn set_thread_limits(&self, min: u32, max: u32) {
40        unsafe {
41            check(SetThreadpoolThreadMinimum(self.0.Pool, min));
42            SetThreadpoolThreadMaximum(self.0.Pool, max);
43        }
44    }
45
46    /// Submits a closure to the thread pool.
47    ///
48    /// The closure must be `Send + 'static`.
49    pub fn submit<F: FnOnce() + Send + 'static>(&self, f: F) {
50        // SAFETY: the closure has `'static` lifetime, and the boxed callback environment
51        // (`self.0`) is kept alive until `Pool::drop` calls `join` to ensure all callbacks
52        // have finished using it.
53        assert!(
54            unsafe { submit_with_environment(&*self.0, f) },
55            "allocation failed"
56        );
57    }
58
59    /// Create a scope for submitting closures.
60    ///
61    /// Within this scope local variables can be sent to the pool thread for execution.
62    /// This is possible because `scope` will wait for all submitted closures to finish before
63    /// returning. It also waits for closures submitted to the same `Pool` from other threads,
64    /// not just those submitted within this scope.
65    pub fn scope<'env, F>(&self, f: F)
66    where
67        F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>),
68    {
69        struct DropGuard<'a>(&'a Pool);
70        impl Drop for DropGuard<'_> {
71            fn drop(&mut self) {
72                self.0.join();
73            }
74        }
75        // Ensure that we always join the pool before returning.
76        let _guard = DropGuard(self);
77        let scope = Scope {
78            pool: self,
79            env: PhantomData,
80            scope: PhantomData,
81        };
82        f(&scope);
83    }
84
85    /// Waits for all submissions to finish.
86    ///
87    /// Dropping the `Pool` will also wait for all submissions to finish.
88    pub fn join(&self) {
89        unsafe {
90            CloseThreadpoolCleanupGroupMembers(self.0.CleanupGroup, 0, core::ptr::null_mut());
91        }
92    }
93}
94
95impl Default for Pool {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101unsafe impl Sync for Pool {}
102unsafe impl Send for Pool {}
103
104impl Drop for Pool {
105    fn drop(&mut self) {
106        // The `Pool` cannot be dropped without waiting for all closures to complete, as their
107        // lifetimes are only guaranteed to be as long as the `Pool` object.
108        self.join();
109
110        unsafe {
111            CloseThreadpoolCleanupGroup(self.0.CleanupGroup);
112            CloseThreadpool(self.0.Pool);
113        }
114    }
115}
116
117/// A scope to submit closures in.
118///
119/// See [`scope`][Pool::scope] for details.
120pub struct Scope<'scope, 'env: 'scope> {
121    pool: &'scope Pool,
122    scope: PhantomData<&'scope mut &'scope ()>,
123    env: PhantomData<&'env mut &'env ()>,
124}
125
126impl<'scope, 'env> Scope<'scope, 'env> {
127    /// Submits the closure to run on the `Pool`.
128    ///
129    /// The closure cannot outlive the `Scope` it's run in.
130    pub fn submit<F: FnOnce() + Send + 'scope>(&'scope self, f: F) {
131        assert!(
132            unsafe { submit_with_environment(&*self.pool.0, f) },
133            "allocation failed"
134        );
135    }
136}
137
138impl Deref for Scope<'_, '_> {
139    type Target = Pool;
140    fn deref(&self) -> &Self::Target {
141        self.pool
142    }
143}