| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::thread::JoinHandle; |
| 4 | |
| 5 | use tokio::task::JoinHandle as TaskHandle; |
| 6 | |
| 7 | /// A running frame source; dropping it stops the capture. |
| 8 | pub enum Capture { |
| 9 | Thread { stop: Arc<AtomicBool>, thread: Option<JoinHandle<()>> }, |
| 10 | Task(TaskHandle<()>), |
| 11 | } |
| 12 | |
| 13 | impl Capture { |
| 14 | pub fn spawn_thread(name: &str, body: impl FnOnce(Arc<AtomicBool>) + Send + 'static) -> std::io::Result<Self> { |
| 15 | let stop = Arc::new(AtomicBool::new(false)); |
| 16 | let thread_stop = stop.clone(); |
| 17 | let thread = std::thread::Builder::new().name(name.to_owned()).spawn(move || body(thread_stop))?; |
| 18 | Ok(Capture::Thread { stop, thread: Some(thread) }) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | impl Drop for Capture { |
| 23 | fn drop(&mut self) { |
| 24 | match self { |
| 25 | Capture::Thread { stop, thread } => { |
| 26 | stop.store(true, Ordering::SeqCst); |
| 27 | if let Some(thread) = thread.take() { |
| 28 | let _ = thread.join(); |
| 29 | } |
| 30 | } |
| 31 | Capture::Task(task) => task.abort(), |
| 32 | } |
| 33 | } |
| 34 | } |