2023-05-25 17:04:51 +10:00
|
|
|
//! A thin wrapper around [`stdx::thread::Pool`] which threads a sender through spawned jobs.
|
|
|
|
//! It is used in [`crate::global_state::GlobalState`] throughout the main loop.
|
2023-05-20 22:29:32 +10:00
|
|
|
|
2020-06-25 15:35:42 +02:00
|
|
|
use crossbeam_channel::Sender;
|
2023-05-27 03:18:17 +10:00
|
|
|
use stdx::thread::{Pool, ThreadIntent};
|
2020-06-25 15:35:42 +02:00
|
|
|
|
|
|
|
pub(crate) struct TaskPool<T> {
|
|
|
|
sender: Sender<T>,
|
2023-05-25 17:04:51 +10:00
|
|
|
pool: Pool,
|
2020-06-25 15:35:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> TaskPool<T> {
|
2022-12-09 21:11:46 +08:00
|
|
|
pub(crate) fn new_with_threads(sender: Sender<T>, threads: usize) -> TaskPool<T> {
|
2023-05-25 17:04:51 +10:00
|
|
|
TaskPool { sender, pool: Pool::new(threads) }
|
2020-06-25 15:35:42 +02:00
|
|
|
}
|
|
|
|
|
2023-06-04 09:30:21 +02:00
|
|
|
pub(crate) fn spawn<F>(&mut self, intent: ThreadIntent, task: F)
|
|
|
|
where
|
2020-06-25 15:35:42 +02:00
|
|
|
F: FnOnce() -> T + Send + 'static,
|
|
|
|
T: Send + 'static,
|
|
|
|
{
|
2023-05-27 03:18:17 +10:00
|
|
|
self.pool.spawn(intent, {
|
2020-06-25 15:35:42 +02:00
|
|
|
let sender = self.sender.clone();
|
2023-06-04 09:30:21 +02:00
|
|
|
move || sender.send(task()).unwrap()
|
2020-06-25 15:35:42 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-06-04 09:30:21 +02:00
|
|
|
pub(crate) fn spawn_with_sender<F>(&mut self, intent: ThreadIntent, task: F)
|
|
|
|
where
|
2020-10-06 17:58:03 +02:00
|
|
|
F: FnOnce(Sender<T>) + Send + 'static,
|
|
|
|
T: Send + 'static,
|
|
|
|
{
|
2023-05-27 03:18:17 +10:00
|
|
|
self.pool.spawn(intent, {
|
2020-10-06 17:58:03 +02:00
|
|
|
let sender = self.sender.clone();
|
2023-06-04 09:30:21 +02:00
|
|
|
move || task(sender)
|
2020-10-06 17:58:03 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:35:42 +02:00
|
|
|
pub(crate) fn len(&self) -> usize {
|
2023-05-25 17:04:51 +10:00
|
|
|
self.pool.len()
|
2020-06-25 15:35:42 +02:00
|
|
|
}
|
|
|
|
}
|