windows_threading/
pool.rs1use super::*;
2use core::{marker::PhantomData, ops::Deref};
3
4pub struct Pool(Box<TP_CALLBACK_ENVIRON_V3>);
9
10impl Pool {
11 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 Self(Box::new(e))
27 }
28
29 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 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 pub fn submit<F: FnOnce() + Send + 'static>(&self, f: F) {
50 assert!(
54 unsafe { submit_with_environment(&*self.0, f) },
55 "allocation failed"
56 );
57 }
58
59 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 let _guard = DropGuard(self);
77 let scope = Scope {
78 pool: self,
79 env: PhantomData,
80 scope: PhantomData,
81 };
82 f(&scope);
83 }
84
85 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 self.join();
109
110 unsafe {
111 CloseThreadpoolCleanupGroup(self.0.CleanupGroup);
112 CloseThreadpool(self.0.Pool);
113 }
114 }
115}
116
117pub 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 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}