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
108
109
110
111
112
113
114
115
use core::prelude::*;
use core::ty::Unsafe;
use mutex;
pub struct Exclusive<T> {
lock: mutex::NativeMutex,
data: Unsafe<T>,
}
pub struct ExclusiveGuard<'a, T> {_data: &'a mut T,
_guard: mutex::LockGuard<'a>,
}
impl<T: Send> Exclusive<T> {
pub fn new(user_data: T) -> Exclusive<T> {
Exclusive {
lock: unsafe { mutex::NativeMutex::new() },
data: Unsafe::new(user_data),
}
}
pub unsafe fn lock<'a>(&'a self) -> ExclusiveGuard<'a, T> {
let guard = self.lock.lock();
let data = &mut *self.data.get();
ExclusiveGuard {
_data: data,
_guard: guard,
}
}
}
impl<'a, T: Send> ExclusiveGuard<'a, T> {pub fn signal(&self) {
unsafe { self._guard.signal() }
}
pub fn wait(&self) {
unsafe { self._guard.wait() }
}
}
impl<'a, T: Send> Deref<T> for ExclusiveGuard<'a, T> {
fn deref<'a>(&'a self) -> &'a T { &*self._data }
}
impl<'a, T: Send> DerefMut<T> for ExclusiveGuard<'a, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut *self._data }
}
#[cfg(test)]
mod tests {
use std::prelude::*;
use alloc::arc::Arc;
use super::Exclusive;
use std::task;
#[test]
fn exclusive_new_arc() {
unsafe {
let mut futures = Vec::new();
let num_tasks = 10;
let count = 10;
let total = Arc::new(Exclusive::new(box 0));
for _ in range(0u, num_tasks) {
let total = total.clone();
let (tx, rx) = channel();
futures.push(rx);
task::spawn(proc() {
for _ in range(0u, count) {
**total.lock() += 1;
}
tx.send(());
});
};
for f in futures.mut_iter() { f.recv() }
assert_eq!(**total.lock(), num_tasks * count);
}
}
}