6
6
mod example {
7
7
#![ allow( dead_code) ]
8
8
9
- use std:: cell:: UnsafeCell ;
10
9
use std:: ops:: { Deref , DerefMut } ;
11
- use std:: sync:: atomic:: { AtomicBool , Ordering } ;
12
10
use std:: sync:: { mpsc, Arc } ;
13
11
use std:: thread;
14
12
use std:: time:: { Duration , Instant } ;
15
13
16
14
use event_listener:: { listener, Event , Listener } ;
15
+ use try_lock:: { Locked , TryLock } ;
17
16
18
17
/// A simple mutex.
19
18
struct Mutex < T > {
20
- /// Set to `true` when the mutex is locked.
21
- locked : AtomicBool ,
22
-
23
19
/// Blocked lock operations.
24
20
lock_ops : Event ,
25
21
26
- /// The inner protected data .
27
- data : UnsafeCell < T > ,
22
+ /// The inner non-blocking mutex .
23
+ data : TryLock < T > ,
28
24
}
29
25
30
26
unsafe impl < T : Send > Send for Mutex < T > { }
@@ -34,19 +30,14 @@ mod example {
34
30
/// Creates a mutex.
35
31
fn new ( t : T ) -> Mutex < T > {
36
32
Mutex {
37
- locked : AtomicBool :: new ( false ) ,
38
33
lock_ops : Event :: new ( ) ,
39
- data : UnsafeCell :: new ( t) ,
34
+ data : TryLock :: new ( t) ,
40
35
}
41
36
}
42
37
43
38
/// Attempts to acquire a lock.
44
39
fn try_lock ( & self ) -> Option < MutexGuard < ' _ , T > > {
45
- if !self . locked . swap ( true , Ordering :: Acquire ) {
46
- Some ( MutexGuard ( self ) )
47
- } else {
48
- None
49
- }
40
+ self . data . try_lock ( ) . map ( MutexGuard )
50
41
}
51
42
52
43
/// Blocks until a lock is acquired.
@@ -116,29 +107,19 @@ mod example {
116
107
}
117
108
118
109
/// A guard holding a lock.
119
- struct MutexGuard < ' a , T > ( & ' a Mutex < T > ) ;
120
-
121
- unsafe impl < T : Send > Send for MutexGuard < ' _ , T > { }
122
- unsafe impl < T : Sync > Sync for MutexGuard < ' _ , T > { }
123
-
124
- impl < T > Drop for MutexGuard < ' _ , T > {
125
- fn drop ( & mut self ) {
126
- self . 0 . locked . store ( false , Ordering :: Release ) ;
127
- self . 0 . lock_ops . notify ( 1 ) ;
128
- }
129
- }
110
+ struct MutexGuard < ' a , T > ( Locked < ' a , T > ) ;
130
111
131
112
impl < T > Deref for MutexGuard < ' _ , T > {
132
113
type Target = T ;
133
114
134
115
fn deref ( & self ) -> & T {
135
- unsafe { & * self . 0 . data . get ( ) }
116
+ & self . 0
136
117
}
137
118
}
138
119
139
120
impl < T > DerefMut for MutexGuard < ' _ , T > {
140
121
fn deref_mut ( & mut self ) -> & mut T {
141
- unsafe { & mut * self . 0 . data . get ( ) }
122
+ & mut self . 0
142
123
}
143
124
}
144
125
0 commit comments