| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::thread::JoinHandle; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use tokio::task::JoinHandle as TaskHandle; |
| 7 | |
| 8 | const STOP_WAIT: Duration = Duration::from_secs(2); |
| 9 | const STOP_POLL: Duration = Duration::from_millis(5); |
| 10 | |
| 11 | /// A running frame source; dropping it stops the capture. |
| 12 | pub enum Capture { |
| 13 | Thread { stop: Arc<AtomicBool>, thread: Option<JoinHandle<()>> }, |
| 14 | Task(TaskHandle<()>), |
| 15 | } |
| 16 | |
| 17 | impl Capture { |
| 18 | pub fn spawn_thread(name: &str, body: impl FnOnce(Arc<AtomicBool>) + Send + 'static) -> std::io::Result<Self> { |
| 19 | let stop = Arc::new(AtomicBool::new(false)); |
| 20 | let thread_stop = stop.clone(); |
| 21 | let thread = std::thread::Builder::new().name(name.to_owned()).spawn(move || body(thread_stop))?; |
| 22 | Ok(Capture::Thread { stop, thread: Some(thread) }) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | impl Drop for Capture { |
| 27 | fn drop(&mut self) { |
| 28 | match self { |
| 29 | Capture::Thread { stop, thread } => { |
| 30 | stop.store(true, Ordering::SeqCst); |
| 31 | let Some(thread) = thread.take() else { return }; |
| 32 | let started = Instant::now(); |
| 33 | while !thread.is_finished() && started.elapsed() < STOP_WAIT { |
| 34 | std::thread::sleep(STOP_POLL); |
| 35 | } |
| 36 | if thread.is_finished() { |
| 37 | let _ = thread.join(); |
| 38 | } |
| 39 | } |
| 40 | Capture::Task(task) => task.abort(), |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[cfg(test)] |
| 46 | mod tests { |
| 47 | use std::time::{Duration, Instant}; |
| 48 | |
| 49 | use super::Capture; |
| 50 | |
| 51 | #[test] |
| 52 | fn a_stuck_capture_thread_does_not_hold_up_the_caller() { |
| 53 | let capture = Capture::spawn_thread("stuck", |_| loop { |
| 54 | std::thread::sleep(Duration::from_secs(60)); |
| 55 | }) |
| 56 | .unwrap(); |
| 57 | let started = Instant::now(); |
| 58 | drop(capture); |
| 59 | assert!(started.elapsed() < Duration::from_secs(5)); |
| 60 | } |
| 61 | |
| 62 | #[test] |
| 63 | fn a_stopped_capture_thread_is_joined() { |
| 64 | let capture = Capture::spawn_thread("quick", |stop| { |
| 65 | while !stop.load(std::sync::atomic::Ordering::SeqCst) { |
| 66 | std::thread::sleep(Duration::from_millis(5)); |
| 67 | } |
| 68 | }) |
| 69 | .unwrap(); |
| 70 | let started = Instant::now(); |
| 71 | drop(capture); |
| 72 | assert!(started.elapsed() < Duration::from_secs(1)); |
| 73 | } |
| 74 | } |