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
#[cfg(feature = "crossbeam")]
use crossbeam::{unbounded as channel, Sender};
#[cfg(feature = "crossbeam")]
pub use crossbeam::{Receiver, TryRecvError};
#[cfg(not(feature = "crossbeam"))]
use std::sync::mpsc::{channel, Sender};
#[cfg(not(feature = "crossbeam"))]
pub use std::sync::mpsc::{Receiver, TryRecvError};
use std::{mem::ManuallyDrop, ops::Deref, thread::JoinHandle};
pub struct DropWorker<T> {
sender: ManuallyDrop<Sender<T>>,
thread: JoinHandle<()>,
}
#[macro_export]
macro_rules! try_err {
($recv:expr) => {
if let Err(drop_worker::TryRecvError::Disconnected) = $recv.try_recv() {
return;
}
};
}
#[macro_export]
macro_rules! recv_data {
($recv:expr) => {
if let Ok(data) = $recv.recv() {
data
} else {
return;
};
};
}
impl<T: Send + 'static> DropWorker<T> {
pub fn new<F: Fn(Receiver<T>) + Send + 'static>(func: F) -> Self {
let (sender, receiver) = channel::<T>();
let sender = ManuallyDrop::new(sender);
let thread = std::thread::spawn(move || func(receiver));
DropWorker { sender, thread }
}
}
impl<T: Send + 'static> Deref for DropWorker<T> {
type Target = ManuallyDrop<Sender<T>>;
fn deref(&self) -> &Self::Target {
&self.sender
}
}
impl<T> Drop for DropWorker<T> {
fn drop(&mut self) {
let thread;
unsafe {
ManuallyDrop::drop(&mut self.sender);
thread = std::mem::replace(&mut self.thread, std::thread::spawn(|| ()));
}
let _ = thread.join();
}
}