BlueGit

ict rusty-teams

Files

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

capture.rs

capture.rs 3.1 KiB Download Raw
1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::{Arc, Mutex};
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
11static STOPPING: Mutex<Vec<JoinHandle<()>>> = Mutex::new(Vec::new());
12
13fn wait_for_stopping_captures() {
14 let started = Instant::now();
15 loop {
16 let mut stopping = STOPPING
17 .lock()
18 .unwrap_or_else(|poisoned| poisoned.into_inner());
19 let (finished, running): (Vec<_>, Vec<_>) = std::mem::take(&mut *stopping)
20 .into_iter()
21 .partition(|thread| thread.is_finished());
22 *stopping = running;
23 let idle = stopping.is_empty();
24 drop(stopping);
25 for thread in finished {
26 let _ = thread.join();
27 }
28 if idle || started.elapsed() >= STOP_WAIT {
29 return;
30 }
31 std::thread::sleep(STOP_POLL);
32 }
33}
34
35/// A running frame source; dropping it stops the capture.
36pub enum Capture {
37 Thread {
38 stop: Arc<AtomicBool>,
39 thread: Option<JoinHandle<()>>,
40 },
41 Task(TaskHandle<()>),
42}
43
44impl Capture {
45 pub fn spawn_thread(
46 name: &str,
47 body: impl FnOnce(Arc<AtomicBool>) + Send + 'static,
48 ) -> std::io::Result<Self> {
49 let stop = Arc::new(AtomicBool::new(false));
50 let thread_stop = stop.clone();
51 let thread = std::thread::Builder::new()
52 .name(name.to_owned())
53 .spawn(move || {
54 wait_for_stopping_captures();
55 body(thread_stop)
56 })?;
57 Ok(Capture::Thread {
58 stop,
59 thread: Some(thread),
60 })
61 }
62}
63
64impl Drop for Capture {
65 fn drop(&mut self) {
66 match self {
67 Capture::Thread { stop, thread } => {
68 stop.store(true, Ordering::SeqCst);
69 if let Some(thread) = thread.take() {
70 STOPPING
71 .lock()
72 .unwrap_or_else(|poisoned| poisoned.into_inner())
73 .push(thread);
74 }
75 }
76 Capture::Task(task) => task.abort(),
77 }
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use std::time::{Duration, Instant};
84
85 use super::Capture;
86
87 #[test]
88 fn a_stuck_capture_thread_does_not_hold_up_the_caller() {
89 let capture = Capture::spawn_thread("stuck", |_| {
90 loop {
91 std::thread::sleep(Duration::from_secs(60));
92 }
93 })
94 .unwrap();
95 let started = Instant::now();
96 drop(capture);
97 assert!(started.elapsed() < Duration::from_secs(5));
98 }
99
100 #[test]
101 fn a_stopped_capture_thread_is_joined() {
102 let capture = Capture::spawn_thread("quick", |stop| {
103 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
104 std::thread::sleep(Duration::from_millis(5));
105 }
106 })
107 .unwrap();
108 let started = Instant::now();
109 drop(capture);
110 assert!(started.elapsed() < Duration::from_secs(1));
111 }
112}