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