1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use std::io;
use std::sync::{Arc, Mutex, Weak};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{Builder, JoinHandle};
use std::time::{Duration, Instant};
struct Canary {
alive: AtomicBool,
thread: Mutex<Option<JoinHandle<()>>>,
}
impl Canary {
fn new() -> Self {
Self {
alive: AtomicBool::new(true),
thread: Mutex::new(None),
}
}
}
pub struct RunLoop {
flag: Weak<Canary>,
}
impl RunLoop {
pub fn new<F, T>(fun: F) -> io::Result<Self>
where
F: FnOnce(&Fn() -> bool) -> T,
F: Send + 'static,
{
Self::new_with_timeout(fun, 0 )
}
pub fn new_with_timeout<F, T>(fun: F, timeout_ms: u64) -> io::Result<Self>
where
F: FnOnce(&Fn() -> bool) -> T,
F: Send + 'static,
{
let flag = Arc::new(Canary::new());
let flag_ = flag.clone();
let thread = Builder::new().spawn(move || {
let timeout = Duration::from_millis(timeout_ms);
let start = Instant::now();
let still_alive = || {
flag.alive.load(Ordering::Relaxed) &&
(timeout_ms == 0 || start.elapsed() < timeout)
};
let _ = fun(&still_alive);
})?;
let mut guard = (*flag_).thread.lock().map_err(|_| {
io::Error::new(io::ErrorKind::Other, "failed to lock")
})?;
*guard = Some(thread);
Ok(Self { flag: Arc::downgrade(&flag_) })
}
pub fn cancel(&self) {
if let Some(flag) = self.flag.upgrade() {
flag.alive.store(false, Ordering::Relaxed);
if let Ok(mut guard) = flag.thread.lock() {
if let Some(handle) = (*guard).take() {
let _ = handle.join();
}
}
}
}
pub fn alive(&self) -> bool {
if let Some(flag) = self.flag.upgrade() {
flag.alive.load(Ordering::Relaxed)
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Barrier};
use std::sync::mpsc::channel;
use super::RunLoop;
#[test]
fn test_empty() {
let rloop = RunLoop::new(|_| {}).unwrap();
while rloop.alive() { }
rloop.cancel();
}
#[test]
fn test_cancel_early() {
RunLoop::new(|alive| assert!(!alive())).unwrap().cancel();
}
#[test]
fn test_cancel_endless_loop() {
let barrier = Arc::new(Barrier::new(2));
let b = barrier.clone();
let rloop = RunLoop::new(move |alive| {
b.wait();
while alive() { }
}).unwrap();
barrier.wait();
assert!(rloop.alive());
rloop.cancel();
assert!(!rloop.alive());
}
#[test]
fn test_timeout() {
let rloop = RunLoop::new_with_timeout(|alive| while alive() {}, 1).unwrap();
while rloop.alive() { }
assert!(!rloop.alive());
rloop.cancel();
}
#[test]
fn test_channel() {
let (tx, rx) = channel();
let rloop = RunLoop::new(move |alive| while alive() {
tx.send(0u8).unwrap();
}).unwrap();
assert_eq!(rx.recv().unwrap(), 0u8);
assert!(rloop.alive());
rloop.cancel();
assert!(!rloop.alive());
}
}