@@ -36,10 +36,14 @@ pub struct ThreadPool {
36
36
sender : Option < Sender < Task > > ,
37
37
}
38
38
39
+ type Callback = Arc < dyn Fn ( ) + Send + Sync + ' static > ;
40
+
39
41
/// The builder of [`ThreadPool`].
40
42
pub struct ThreadPoolBuilder {
41
43
capacity : usize ,
42
44
threads : usize ,
45
+ on_thread_spawn : Option < Callback > ,
46
+ on_thread_finish : Option < Callback > ,
43
47
}
44
48
45
49
struct Worker {
@@ -53,6 +57,8 @@ impl ThreadPool {
53
57
ThreadPoolBuilder {
54
58
capacity : 8192 ,
55
59
threads : 1 ,
60
+ on_thread_spawn : None ,
61
+ on_thread_finish : None ,
56
62
}
57
63
}
58
64
@@ -117,6 +123,27 @@ impl ThreadPoolBuilder {
117
123
self
118
124
}
119
125
126
+ /// Provide a function that will be called on each thread of the thread pool
127
+ /// immediately after it is spawned. This can, for example, be used to set
128
+ /// core affinity for each thread.
129
+ pub fn on_thread_spawn < F > ( & mut self , f : F ) -> & mut Self
130
+ where
131
+ F : Fn ( ) + Send + Sync + ' static ,
132
+ {
133
+ self . on_thread_spawn = Some ( Arc :: new ( f) ) ;
134
+ self
135
+ }
136
+
137
+ /// Provide a function that will be called on each thread of the thread pool
138
+ /// just before the thread finishes.
139
+ pub fn on_thread_finish < F > ( & mut self , f : F ) -> & mut Self
140
+ where
141
+ F : Fn ( ) + Send + Sync + ' static ,
142
+ {
143
+ self . on_thread_finish = Some ( Arc :: new ( f) ) ;
144
+ self
145
+ }
146
+
120
147
/// Builds a [`ThreadPool`].
121
148
pub fn build ( & self ) -> Result < ThreadPool > {
122
149
if self . capacity < 1 {
@@ -136,7 +163,20 @@ impl ThreadPoolBuilder {
136
163
let mut threads = Vec :: new ( ) ;
137
164
threads. resize_with ( self . threads , || {
138
165
let receiver = receiver. clone ( ) ;
139
- Some ( thread:: spawn ( move || Worker { receiver } . run ( ) ) )
166
+ let on_thread_spawn = self . on_thread_spawn . clone ( ) ;
167
+ let on_thread_finish = self . on_thread_finish . clone ( ) ;
168
+
169
+ Some ( thread:: spawn ( move || {
170
+ if let Some ( f) = on_thread_spawn {
171
+ f ( ) ;
172
+ }
173
+
174
+ Worker { receiver } . run ( ) ;
175
+
176
+ if let Some ( f) = on_thread_finish {
177
+ f ( ) ;
178
+ }
179
+ } ) )
140
180
} ) ;
141
181
142
182
Ok ( ThreadPool {
0 commit comments