Skip to content

Commit 0d182e2

Browse files
authored
Add on_thread_spawn and on_thread_finish to ThreadPoolBuilder (#54)
1 parent 7e8f264 commit 0d182e2

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

spdlog/src/thread_pool.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,14 @@ pub struct ThreadPool {
3636
sender: Option<Sender<Task>>,
3737
}
3838

39+
type Callback = Arc<dyn Fn() + Send + Sync + 'static>;
40+
3941
/// The builder of [`ThreadPool`].
4042
pub struct ThreadPoolBuilder {
4143
capacity: usize,
4244
threads: usize,
45+
on_thread_spawn: Option<Callback>,
46+
on_thread_finish: Option<Callback>,
4347
}
4448

4549
struct Worker {
@@ -53,6 +57,8 @@ impl ThreadPool {
5357
ThreadPoolBuilder {
5458
capacity: 8192,
5559
threads: 1,
60+
on_thread_spawn: None,
61+
on_thread_finish: None,
5662
}
5763
}
5864

@@ -117,6 +123,27 @@ impl ThreadPoolBuilder {
117123
self
118124
}
119125

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+
120147
/// Builds a [`ThreadPool`].
121148
pub fn build(&self) -> Result<ThreadPool> {
122149
if self.capacity < 1 {
@@ -136,7 +163,20 @@ impl ThreadPoolBuilder {
136163
let mut threads = Vec::new();
137164
threads.resize_with(self.threads, || {
138165
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+
}))
140180
});
141181

142182
Ok(ThreadPool {

0 commit comments

Comments
 (0)