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
#![feature(thread_spawn_unchecked)]
#![feature(test)]
use std::thread;
use std::marker::PhantomData;
use std::io;
struct JoinFlag {
is_joined: bool,
}
impl JoinFlag {
fn new() -> Self {
Self {
is_joined: false,
}
}
fn set_join(mut self) {
self.is_joined = true;
}
}
impl Drop for JoinFlag {
#[inline]
fn drop(&mut self) {
if !self.is_joined {
panic!("handle must be join before dropped")
}
}
}
pub struct BorrowedJoinHandle<'b, T> {
inner: thread::JoinHandle<T>,
join_flag: JoinFlag,
_marker: PhantomData<&'b ()>,
}
impl<'b, T> From<thread::JoinHandle<T>> for BorrowedJoinHandle<'b, T> {
#[inline]
fn from(handle: thread::JoinHandle<T>) -> Self {
Self::new(handle)
}
}
impl<'b, T> BorrowedJoinHandle<'b, T> {
#[inline]
fn new(inner: thread::JoinHandle<T>) -> Self {
Self {
inner,
join_flag: JoinFlag::new(),
_marker: PhantomData,
}
}
#[inline]
pub fn thread(&self) -> &thread::Thread {
self.inner.thread()
}
#[inline]
pub fn join(self) -> thread::Result<T> {
self.join_flag.set_join();
self.inner.join()
}
}
#[inline]
pub fn spawn_with<'b, F, T>(builder: thread::Builder, f: F) -> io::Result<BorrowedJoinHandle<'b, T>>
where
F: FnOnce() -> T,
F: Send + 'b,
T: Send + 'b, {
unsafe {
match builder.spawn_unchecked(f) {
Ok(handle) => Ok(handle.into()),
Err(err) => Err(err),
}
}
}
#[inline]
pub fn spawn<'b, F, T>(f: F) -> BorrowedJoinHandle<'b, T>
where
F: FnOnce() -> T,
F: Send + 'b,
T: Send + 'b,
{
spawn_with(thread::Builder::new(), f).unwrap()
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod bench;