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
|
use std::cell::{Ref, RefCell, RefMut};
use std::thread;
/// TheardGuard is a _runtime_ thread guard for its internal data. It panics if
/// data is being accessed from a thread other than the one that TheardGuard
/// was initialized in.
pub struct ThreadGuard<T> {
thread_id: thread::ThreadId,
data: RefCell<T>,
}
unsafe impl<T> Send for ThreadGuard<T> {}
unsafe impl<T> Sync for ThreadGuard<T> {}
impl<T> ThreadGuard<T> {
pub fn new(data: T) -> Self {
ThreadGuard {
thread_id: thread::current().id(),
data: RefCell::new(data),
}
}
#[allow(unused)]
pub fn borrow(&self) -> Ref<T> {
match self.check_thread() {
Ok(_) => self.data.borrow(),
Err(()) => {
panic!(
"Data is only accessible on thread {:?} (current is {:?})",
self.thread_id,
thread::current().id(),
);
}
}
}
pub fn borrow_mut(&self) -> RefMut<T> {
match self.check_thread() {
Ok(_) => self.data.borrow_mut(),
Err(()) => {
panic!(
"Data is only accessible on thread {:?} (current is {:?})",
self.thread_id,
thread::current().id(),
);
}
}
}
fn check_thread(&self) -> Result<(), ()> {
if self.thread_id == thread::current().id() {
return Ok(());
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn access_denied_across_thread() {
let data = 1;
let guard = ThreadGuard::new(data);
thread::spawn(move || {
guard.borrow();
})
.join()
.unwrap();
}
#[test]
fn access_granted_from_correct_thread() {
let data = 1;
let guard = ThreadGuard::new(data);
guard.borrow();
}
#[test]
fn can_mutate() {
let data = 1;
let guard = ThreadGuard::new(data);
{
let mut data = guard.borrow_mut();
*data = 4;
}
assert_eq!(*guard.borrow(), 4);
}
}
|