diff --git a/actuator/rust/src/lib.rs b/actuator/rust/src/lib.rs index ce63a23..e029acf 100644 --- a/actuator/rust/src/lib.rs +++ b/actuator/rust/src/lib.rs @@ -1,8 +1,9 @@ use pyo3::prelude::*; use pyo3_stub_gen::{define_stub_info_gatherer, derive::gen_stub_pyclass}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use tokio::runtime::Runtime; use tokio::time::{interval, Duration}; +use tokio::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; #[pyclass] @@ -22,24 +23,24 @@ impl Actuator { let runtime_clone = Arc::clone(&runtime); let running_clone = Arc::clone(&running); - std::thread::spawn(move || { - if let Some(rt) = runtime_clone.lock().unwrap().as_ref() { - rt.block_on(async { - let mut interval = interval(Duration::from_secs(1)); - while running_clone.load(Ordering::Relaxed) { - interval.tick().await; - println!("Hello, world!"); - } - }); - } - }); + + // Use the runtime to spawn the background task + if let Some(rt) = runtime_clone.try_lock().unwrap().as_ref() { + rt.spawn(async move { + let mut interval = interval(Duration::from_secs(1)); + while running_clone.load(Ordering::Relaxed) { + interval.tick().await; + println!("Hello, world!"); + } + }); + } Ok(Actuator { runtime, running }) } fn stop(&mut self) -> PyResult<()> { self.running.store(false, Ordering::Relaxed); - if let Some(runtime) = self.runtime.lock().unwrap().take() { + if let Some(runtime) = self.runtime.try_lock().unwrap().take() { runtime.shutdown_background(); } Ok(())