BlueGit

ict rusty-teams

Files

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

capture.rs

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