Skip to main content

akar_common/
task_system.rs

1//! Task system / thread pool for parallel query execution.
2//!
3//! Uses `rayon` under the hood for work-stealing parallelism.
4
5use rayon::ThreadPool;
6use std::sync::Arc;
7
8/// A handle to Akar's task execution system.
9#[derive(Clone)]
10pub struct TaskSystem {
11    pool: Arc<ThreadPool>,
12    num_threads: usize,
13}
14
15impl TaskSystem {
16    /// Create a new task system with the given number of threads.
17    /// If `num_threads` is 0, uses rayon's default (logical CPU count).
18    pub fn new(num_threads: usize) -> Self {
19        let num = if num_threads == 0 {
20            rayon::current_num_threads()
21        } else {
22            num_threads
23        };
24        let pool = Arc::new(
25            rayon::ThreadPoolBuilder::new()
26                .num_threads(num)
27                .thread_name(|i| format!("akar-worker-{i}"))
28                .build()
29                .expect("Failed to build rayon thread pool"),
30        );
31        Self { pool, num_threads: num }
32    }
33
34    pub fn num_threads(&self) -> usize {
35        self.num_threads
36    }
37
38    /// Execute a parallel operation across the thread pool.
39    pub fn install<F, R>(&self, op: F) -> R
40    where
41        F: FnOnce() -> R + Send,
42        R: Send,
43    {
44        self.pool.install(op)
45    }
46}
47
48impl Default for TaskSystem {
49    fn default() -> Self {
50        Self::new(0)
51    }
52}