vortex_io/runtime/
pool.rs1use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::sync::atomic::Ordering;
7use std::time::Duration;
8
9use parking_lot::Mutex;
10use smol::block_on;
11use vortex_error::VortexExpect;
12use vortex_utils::parallelism::get_available_parallelism;
13
14use crate::runtime::smol::SmolExecutor;
15
16#[derive(Clone)]
21pub struct CurrentThreadWorkerPool {
22 executor: Arc<SmolExecutor>,
23 state: Arc<Mutex<PoolState>>,
24}
25
26impl CurrentThreadWorkerPool {
27 pub(super) fn new(executor: Arc<SmolExecutor>) -> Self {
28 Self {
29 executor,
30 state: Arc::new(Mutex::new(PoolState::default())),
31 }
32 }
33
34 pub fn set_workers_to_available_parallelism(&self) {
37 let n = get_available_parallelism()
38 .map(|n| n.saturating_sub(1).max(1))
39 .unwrap_or(1);
40 self.set_workers(n);
41 }
42
43 pub fn set_workers(&self, n: usize) {
47 let mut state = self.state.lock();
48 let current = state.workers.len();
49
50 if n > current {
51 for _ in current..n {
53 let shutdown = Arc::new(AtomicBool::new(false));
54 let executor = Arc::clone(&self.executor);
55 let shutdown_clone = Arc::clone(&shutdown);
56
57 std::thread::Builder::new()
58 .name("vortex-current-thread-worker".to_string())
59 .spawn(move || {
60 block_on(executor.run(async move {
62 while !shutdown_clone.load(Ordering::Relaxed) {
63 smol::Timer::after(Duration::from_millis(100)).await;
64 }
65 }))
66 })
67 .vortex_expect("Failed to spawn current thread worker");
68
69 state.workers.push(WorkerHandle { shutdown });
70 }
71 } else if n < current {
72 state.workers.truncate(n);
74 }
75 }
76
77 pub fn worker_count(&self) -> usize {
79 self.state.lock().workers.len()
80 }
81}
82
83#[derive(Default)]
84struct PoolState {
85 workers: Vec<WorkerHandle>,
87}
88
89struct WorkerHandle {
90 shutdown: Arc<AtomicBool>,
92}
93
94impl Drop for WorkerHandle {
95 fn drop(&mut self) {
96 self.shutdown.store(true, Ordering::Relaxed);
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use std::sync::mpsc;
103 use std::thread;
104 use std::time::Instant;
105
106 use super::*;
107 use crate::runtime::BlockingRuntime;
108 use crate::runtime::current::CurrentThreadRuntime;
109
110 fn run_task(runtime: &CurrentThreadRuntime) {
111 let (tx, rx) = mpsc::channel();
112 runtime
113 .handle()
114 .spawn(async move {
115 let _ = tx.send(());
116 })
117 .detach();
118 rx.recv_timeout(Duration::from_secs(2))
119 .expect("background worker should complete spawned task");
120 }
121
122 fn wait_for_worker_exit(shutdown: &Arc<AtomicBool>) {
123 let deadline = Instant::now() + Duration::from_secs(2);
124 while Arc::strong_count(shutdown) > 1 {
125 assert!(
126 Instant::now() < deadline,
127 "worker thread did not exit after shutdown"
128 );
129 thread::sleep(Duration::from_millis(10));
130 }
131 }
132
133 #[test]
134 fn test_worker_pool_clone_and_shutdown() {
135 let runtime = CurrentThreadRuntime::new();
136 let pool = runtime.new_pool();
137 pool.set_workers(1);
138 let shutdown = Arc::clone(&pool.state.lock().workers[0].shutdown);
139
140 run_task(&runtime);
141
142 drop(pool.clone());
144 assert_eq!(pool.worker_count(), 1);
145 assert!(!shutdown.load(Ordering::Relaxed));
146 run_task(&runtime);
147
148 drop(pool);
150 assert!(shutdown.load(Ordering::Relaxed));
151 wait_for_worker_exit(&shutdown);
152 }
153}