cqlite_core/platform/
threading.rs1use std::sync::Arc;
4use tokio::sync::{Mutex, RwLock, Semaphore};
5
6#[derive(Debug)]
8pub struct ThreadingProvider {
9 cpu_pool: Arc<Semaphore>,
11
12 io_pool: Arc<Semaphore>,
14}
15
16impl Default for ThreadingProvider {
17 fn default() -> Self {
18 Self::new()
19 }
20}
21
22impl ThreadingProvider {
23 pub fn new() -> Self {
25 let cpu_count = num_cpus::get();
26
27 Self {
28 cpu_pool: Arc::new(Semaphore::new(cpu_count)),
29 io_pool: Arc::new(Semaphore::new(cpu_count * 2)),
30 }
31 }
32
33 pub async fn execute_cpu_task<F, T>(&self, task: F) -> crate::Result<T>
35 where
36 F: FnOnce() -> T + Send + 'static,
37 T: Send + 'static,
38 {
39 let _permit = self
40 .cpu_pool
41 .acquire()
42 .await
43 .map_err(|e| crate::Error::storage(e.to_string()))?;
44
45 let result = tokio::task::spawn_blocking(task)
46 .await
47 .map_err(|e| crate::Error::storage(e.to_string()))?;
48
49 Ok(result)
50 }
51
52 pub async fn execute_io_task<F, T>(&self, task: F) -> crate::Result<T>
54 where
55 F: FnOnce() -> T + Send + 'static,
56 T: Send + 'static,
57 {
58 let _permit = self
59 .io_pool
60 .acquire()
61 .await
62 .map_err(|e| crate::Error::storage(e.to_string()))?;
63
64 let result = tokio::task::spawn_blocking(task)
65 .await
66 .map_err(|e| crate::Error::storage(e.to_string()))?;
67
68 Ok(result)
69 }
70
71 pub fn create_mutex<T>(&self, value: T) -> Arc<Mutex<T>> {
73 Arc::new(Mutex::new(value))
74 }
75
76 pub fn create_rwlock<T>(&self, value: T) -> Arc<RwLock<T>> {
78 Arc::new(RwLock::new(value))
79 }
80
81 pub fn cpu_count(&self) -> usize {
83 num_cpus::get()
84 }
85}