wordval_utils/
task_handle.rs1use std::sync::Mutex;
22use tokio::task::JoinHandle;
23
24#[derive(Debug, Default)]
26pub struct TaskHandles {
27 handles: Mutex<Vec<JoinHandle<()>>>,
28}
29
30impl TaskHandles {
31 pub fn push(&self, handle: JoinHandle<()>) {
33 let mut handles = self.handles.lock().unwrap();
34 handles.retain(|h| !h.is_finished());
35 handles.push(handle);
36 }
37
38 pub fn abort_all(&self) {
40 for handle in self.take_all() {
41 handle.abort();
42 }
43 }
44
45 pub fn abort_all_retained(&self) {
48 for handle in self.handles.lock().unwrap().iter() {
49 handle.abort();
50 }
51 }
52
53 pub fn take_all(&self) -> Vec<JoinHandle<()>> {
55 std::mem::take(&mut *self.handles.lock().unwrap())
56 }
57
58 pub fn all_finished(&self) -> bool {
60 self.handles
61 .lock()
62 .unwrap()
63 .iter()
64 .all(JoinHandle::is_finished)
65 }
66
67 pub fn len(&self) -> usize {
69 self.handles.lock().unwrap().len()
70 }
71
72 pub fn is_empty(&self) -> bool {
74 self.len() == 0
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81 use std::sync::Arc;
82 use std::time::Duration;
83
84 #[tokio::test]
85 async fn push_cleans_finished_handles() {
86 let handles = TaskHandles::default();
87 handles.push(tokio::spawn(async {})); tokio::time::sleep(Duration::from_millis(10)).await;
90 handles.push(tokio::spawn(async {})); tokio::time::sleep(Duration::from_millis(10)).await;
92 assert_eq!(handles.len(), 1, "已完成句柄应被 push 顺带清理");
93 }
94
95 #[tokio::test]
96 async fn abort_all_stops_tasks() {
97 let handles = TaskHandles::default();
98 let guard = Arc::new(tokio::sync::Notify::new());
99 let g = guard.clone();
100 handles.push(tokio::spawn(async move {
101 tokio::time::sleep(Duration::from_secs(60)).await;
103 g.notify_one();
104 }));
105 handles.abort_all();
106 tokio::time::sleep(Duration::from_millis(50)).await;
107 assert!(handles.all_finished());
108 }
109
110 #[tokio::test]
111 async fn take_all_empties() {
112 let handles = TaskHandles::default();
113 handles.push(tokio::spawn(async {}));
114 assert_eq!(handles.take_all().len(), 1);
115 assert!(handles.is_empty());
116 }
117}