BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / capture.rs

capture.rs

capture.rs 1.1 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::thread::JoinHandle;
4
5use tokio::task::JoinHandle as TaskHandle;
6
7/// A running frame source; dropping it stops the capture.
8pub enum Capture {
9 Thread { stop: Arc<AtomicBool>, thread: Option<JoinHandle<()>> },
10 Task(TaskHandle<()>),
11}
12
13impl 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
22impl 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}