daemon_base/
concurrency.rs1use std::thread;
7use log::info;
8use crate::error::DaemonError;
9
10pub enum ConcurrencyModel {
12 MultiThreaded,
13 Async,
14}
15
16pub fn execute_task<F>(model: ConcurrencyModel, task: F) -> Result<(), DaemonError>
18where
19 F: FnOnce() -> Result<(), DaemonError> + Send + 'static,
20{
21 match model {
22 ConcurrencyModel::MultiThreaded => {
23 info!("Executing task in multi-threaded mode.");
24 let handle = thread::spawn(move || {
25 if let Err(e) = task() {
26 log::error!("Task failed: {}", e);
27 }
28 });
29 handle.join().map_err(|_| DaemonError::CustomError("Thread panicked".to_string()))?;
30 }
31 ConcurrencyModel::Async => {
32 #[cfg(feature = "async")]
33 {
34 info!("Executing task in async mode.");
35 let runtime = tokio::runtime::Runtime::new()
36 .map_err(|e| DaemonError::CustomError(format!("Failed to create runtime: {}", e)))?;
37 runtime.block_on(async {
38 if let Err(e) = task() {
39 log::error!("Task failed: {}", e);
40 }
41 });
42 }
43 #[cfg(not(feature = "async"))]
44 {
45 return Err(DaemonError::CustomError("Async feature is not enabled".to_string()));
46 }
47 }
48 }
49 Ok(())
50}