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
use std::fmt::Debug;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
pub trait ThreadPool {
type NewError: Debug;
type ExecError: Debug;
fn new(initial: usize) -> Result<Self, Self::NewError>
where
Self: Sized;
fn execute(
&mut self,
f: impl FnOnce() + Send + 'static,
) -> Result<TerminationHandle, Self::ExecError>;
}
#[derive(Clone, Debug, Default)]
pub struct TerminationHandle {
inner: Arc<InnerHandle>,
}
impl TerminationHandle {
pub fn new() -> (Self, Arc<AtomicBool>) {
let result_needed = Arc::new(AtomicBool::new(true));
let inner_handle = Self {
inner: Arc::new(InnerHandle {
result_needed: result_needed.clone(),
}),
};
(inner_handle, result_needed)
}
}
#[derive(Clone, Debug, Default)]
pub struct InnerHandle {
result_needed: Arc<AtomicBool>,
}
impl InnerHandle {
pub fn cancel(&self) {
self.result_needed.store(false, Ordering::SeqCst)
}
}
impl Drop for InnerHandle {
fn drop(&mut self) {
self.cancel()
}
}
#[cfg(test)]
mod tests {
#![allow(unused_variables, clippy::mutex_atomic)]
use super::TerminationHandle;
use std::sync::atomic::Ordering;
#[test]
pub fn termination_handle_does_not_set_flag_while_in_scope() {
let (th, flag) = TerminationHandle::new();
assert_eq!(flag.load(Ordering::SeqCst), true);
}
#[test]
pub fn termination_handle_sets_flag_when_out_of_scope() {
let flag = {
let (th, flag) = TerminationHandle::new();
flag
};
assert_eq!(flag.load(Ordering::SeqCst), false);
}
#[test]
pub fn termination_handle_does_not_set_flag_until_all_clones_out_of_scope() {
let flag = {
let (th1, flag) = TerminationHandle::new();
{
#[allow(clippy::redundant_clone)]
let th2 = th1.clone();
assert_eq!(flag.load(Ordering::SeqCst), true);
}
assert_eq!(flag.load(Ordering::SeqCst), true);
flag
};
assert_eq!(flag.load(Ordering::SeqCst), false);
}
}