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
use crate::collector::{Collector, LocalHandle};
use crate::guard::Guard;
use crate::primitive::thread_local;
#[cfg(not(crossbeam_loom))]
use once_cell::sync::Lazy;
#[cfg(not(crossbeam_loom))]
static COLLECTOR: Lazy<Collector> = Lazy::new(Collector::new);
#[cfg(crossbeam_loom)]
loom::lazy_static! {
static ref COLLECTOR: Collector = Collector::new();
}
thread_local! {
static HANDLE: LocalHandle = COLLECTOR.register();
}
#[inline]
pub fn pin() -> Guard {
with_handle(|handle| handle.pin())
}
#[inline]
pub fn is_pinned() -> bool {
with_handle(|handle| handle.is_pinned())
}
pub fn default_collector() -> &'static Collector {
&COLLECTOR
}
#[inline]
fn with_handle<F, R>(mut f: F) -> R
where
F: FnMut(&LocalHandle) -> R,
{
HANDLE
.try_with(|h| f(h))
.unwrap_or_else(|_| f(&COLLECTOR.register()))
}
#[cfg(all(test, not(crossbeam_loom)))]
mod tests {
use crossbeam_utils::thread;
#[test]
fn pin_while_exiting() {
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
super::pin();
}
}
thread_local! {
static FOO: Foo = Foo;
}
thread::scope(|scope| {
scope.spawn(|_| {
FOO.with(|_| ());
super::pin();
});
})
.unwrap();
}
}