1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use ops::{Deref, DerefMut};
16 use sync::poison::{self, LockResult, TryLockError, TryLockResult};
17 use sys_common::rwlock as sys;
19 /// A reader-writer lock
21 /// This type of lock allows a number of readers or at most one writer at any
22 /// point in time. The write portion of this lock typically allows modification
23 /// of the underlying data (exclusive access) and the read portion of this lock
24 /// typically allows for read-only access (shared access).
26 /// The type parameter `T` represents the data that this lock protects. It is
27 /// required that `T` satisfies `Send` to be shared across tasks and `Sync` to
28 /// allow concurrent access through readers. The RAII guards returned from the
29 /// locking methods implement `Deref` (and `DerefMut` for the `write` methods)
30 /// to allow access to the contained of the lock.
34 /// RwLocks, like Mutexes, will become poisoned on panics. Note, however, that
35 /// an RwLock may only be poisoned if a panic occurs while it is locked
36 /// exclusively (write mode). If a panic occurs in any reader, then the lock
37 /// will not be poisoned.
42 /// use std::sync::RwLock;
44 /// let lock = RwLock::new(5i);
46 /// // many reader locks can be held at once
48 /// let r1 = lock.read().unwrap();
49 /// let r2 = lock.read().unwrap();
50 /// assert_eq!(*r1, 5);
51 /// assert_eq!(*r2, 5);
52 /// } // read locks are dropped at this point
54 /// // only one write lock may be held, however
56 /// let mut w = lock.write().unwrap();
58 /// assert_eq!(*w, 6);
59 /// } // write lock is dropped here
62 pub struct RwLock<T> {
63 inner: Box<StaticRwLock>,
67 unsafe impl<T:'static+Send> Send for RwLock<T> {}
68 unsafe impl<T> Sync for RwLock<T> {}
70 /// Structure representing a statically allocated RwLock.
72 /// This structure is intended to be used inside of a `static` and will provide
73 /// automatic global access as well as lazy initialization. The internal
74 /// resources of this RwLock, however, must be manually deallocated.
79 /// use std::sync::{StaticRwLock, RW_LOCK_INIT};
81 /// static LOCK: StaticRwLock = RW_LOCK_INIT;
84 /// let _g = LOCK.read().unwrap();
85 /// // ... shared read access
88 /// let _g = LOCK.write().unwrap();
89 /// // ... exclusive write access
91 /// unsafe { LOCK.destroy() } // free all resources
93 #[unstable = "may be merged with RwLock in the future"]
94 pub struct StaticRwLock {
99 unsafe impl Send for StaticRwLock {}
100 unsafe impl Sync for StaticRwLock {}
102 /// Constant initialization for a statically-initialized rwlock.
103 #[unstable = "may be merged with RwLock in the future"]
104 pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock {
105 lock: sys::RWLOCK_INIT,
106 poison: poison::FLAG_INIT,
109 /// RAII structure used to release the shared read access of a lock when
113 #[cfg(stage0)] // NOTE remove impl after next snapshot
114 pub struct RwLockReadGuard<'a, T: 'a> {
115 __lock: &'a StaticRwLock,
116 __data: &'a UnsafeCell<T>,
117 __marker: marker::NoSend,
120 /// RAII structure used to release the shared read access of a lock when
124 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
125 pub struct RwLockReadGuard<'a, T: 'a> {
126 __lock: &'a StaticRwLock,
127 __data: &'a UnsafeCell<T>,
130 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
131 impl<'a, T> !marker::Send for RwLockReadGuard<'a, T> {}
133 /// RAII structure used to release the exclusive write access of a lock when
137 #[cfg(stage0)] // NOTE remove impl after next snapshot
138 pub struct RwLockWriteGuard<'a, T: 'a> {
139 __lock: &'a StaticRwLock,
140 __data: &'a UnsafeCell<T>,
141 __poison: poison::Guard,
142 __marker: marker::NoSend,
145 /// RAII structure used to release the exclusive write access of a lock when
149 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
150 pub struct RwLockWriteGuard<'a, T: 'a> {
151 __lock: &'a StaticRwLock,
152 __data: &'a UnsafeCell<T>,
153 __poison: poison::Guard,
156 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
157 impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {}
159 impl<T: Send + Sync> RwLock<T> {
160 /// Creates a new instance of an RwLock which is unlocked and read to go.
162 pub fn new(t: T) -> RwLock<T> {
163 RwLock { inner: box RW_LOCK_INIT, data: UnsafeCell::new(t) }
166 /// Locks this rwlock with shared read access, blocking the current thread
167 /// until it can be acquired.
169 /// The calling thread will be blocked until there are no more writers which
170 /// hold the lock. There may be other readers currently inside the lock when
171 /// this method returns. This method does not provide any guarantees with
172 /// respect to the ordering of whether contentious readers or writers will
173 /// acquire the lock first.
175 /// Returns an RAII guard which will release this thread's shared access
176 /// once it is dropped.
180 /// This function will return an error if the RwLock is poisoned. An RwLock
181 /// is poisoned whenever a writer panics while holding an exclusive lock.
182 /// The failure will occur immediately after the lock has been acquired.
185 pub fn read(&self) -> LockResult<RwLockReadGuard<T>> {
186 unsafe { self.inner.lock.read() }
187 RwLockReadGuard::new(&*self.inner, &self.data)
190 /// Attempt to acquire this lock with shared read access.
192 /// This function will never block and will return immediately if `read`
193 /// would otherwise succeed. Returns `Some` of an RAII guard which will
194 /// release the shared access of this thread when dropped, or `None` if the
195 /// access could not be granted. This method does not provide any
196 /// guarantees with respect to the ordering of whether contentious readers
197 /// or writers will acquire the lock first.
201 /// This function will return an error if the RwLock is poisoned. An RwLock
202 /// is poisoned whenever a writer panics while holding an exclusive lock. An
203 /// error will only be returned if the lock would have otherwise been
207 pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
208 if unsafe { self.inner.lock.try_read() } {
209 Ok(try!(RwLockReadGuard::new(&*self.inner, &self.data)))
211 Err(TryLockError::WouldBlock)
215 /// Lock this rwlock with exclusive write access, blocking the current
216 /// thread until it can be acquired.
218 /// This function will not return while other writers or other readers
219 /// currently have access to the lock.
221 /// Returns an RAII guard which will drop the write access of this rwlock
226 /// This function will return an error if the RwLock is poisoned. An RwLock
227 /// is poisoned whenever a writer panics while holding an exclusive lock.
228 /// An error will be returned when the lock is acquired.
231 pub fn write(&self) -> LockResult<RwLockWriteGuard<T>> {
232 unsafe { self.inner.lock.write() }
233 RwLockWriteGuard::new(&*self.inner, &self.data)
236 /// Attempt to lock this rwlock with exclusive write access.
238 /// This function does not ever block, and it will return `None` if a call
239 /// to `write` would otherwise block. If successful, an RAII guard is
244 /// This function will return an error if the RwLock is poisoned. An RwLock
245 /// is poisoned whenever a writer panics while holding an exclusive lock. An
246 /// error will only be returned if the lock would have otherwise been
250 pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
251 if unsafe { self.inner.lock.try_read() } {
252 Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data)))
254 Err(TryLockError::WouldBlock)
261 impl<T> Drop for RwLock<T> {
263 unsafe { self.inner.lock.destroy() }
267 struct Dummy(UnsafeCell<()>);
268 unsafe impl Sync for Dummy {}
269 static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
272 /// Locks this rwlock with shared read access, blocking the current thread
273 /// until it can be acquired.
275 /// See `RwLock::read`.
277 #[unstable = "may be merged with RwLock in the future"]
278 pub fn read(&'static self) -> LockResult<RwLockReadGuard<'static, ()>> {
279 unsafe { self.lock.read() }
280 RwLockReadGuard::new(self, &DUMMY.0)
283 /// Attempt to acquire this lock with shared read access.
285 /// See `RwLock::try_read`.
287 #[unstable = "may be merged with RwLock in the future"]
288 pub fn try_read(&'static self)
289 -> TryLockResult<RwLockReadGuard<'static, ()>> {
290 if unsafe { self.lock.try_read() } {
291 Ok(try!(RwLockReadGuard::new(self, &DUMMY.0)))
293 Err(TryLockError::WouldBlock)
297 /// Lock this rwlock with exclusive write access, blocking the current
298 /// thread until it can be acquired.
300 /// See `RwLock::write`.
302 #[unstable = "may be merged with RwLock in the future"]
303 pub fn write(&'static self) -> LockResult<RwLockWriteGuard<'static, ()>> {
304 unsafe { self.lock.write() }
305 RwLockWriteGuard::new(self, &DUMMY.0)
308 /// Attempt to lock this rwlock with exclusive write access.
310 /// See `RwLock::try_write`.
312 #[unstable = "may be merged with RwLock in the future"]
313 pub fn try_write(&'static self)
314 -> TryLockResult<RwLockWriteGuard<'static, ()>> {
315 if unsafe { self.lock.try_write() } {
316 Ok(try!(RwLockWriteGuard::new(self, &DUMMY.0)))
318 Err(TryLockError::WouldBlock)
322 /// Deallocate all resources associated with this static lock.
324 /// This method is unsafe to call as there is no guarantee that there are no
325 /// active users of the lock, and this also doesn't prevent any future users
326 /// of this lock. This method is required to be called to not leak memory on
328 #[unstable = "may be merged with RwLock in the future"]
329 pub unsafe fn destroy(&'static self) {
334 impl<'rwlock, T> RwLockReadGuard<'rwlock, T> {
335 #[cfg(stage0)] // NOTE remove impl after next snapshot
336 fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>)
337 -> LockResult<RwLockReadGuard<'rwlock, T>> {
338 poison::map_result(lock.poison.borrow(), |_| {
342 __marker: marker::NoSend,
347 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
348 fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>)
349 -> LockResult<RwLockReadGuard<'rwlock, T>> {
350 poison::map_result(lock.poison.borrow(), |_| {
358 impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> {
359 #[cfg(stage0)] // NOTE remove impl after next snapshot
360 fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>)
361 -> LockResult<RwLockWriteGuard<'rwlock, T>> {
362 poison::map_result(lock.poison.borrow(), |guard| {
367 __marker: marker::NoSend,
372 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
373 fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>)
374 -> LockResult<RwLockWriteGuard<'rwlock, T>> {
375 poison::map_result(lock.poison.borrow(), |guard| {
386 impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> {
389 fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
392 impl<'rwlock, T> Deref for RwLockWriteGuard<'rwlock, T> {
395 fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
398 impl<'rwlock, T> DerefMut for RwLockWriteGuard<'rwlock, T> {
399 fn deref_mut(&mut self) -> &mut T {
400 unsafe { &mut *self.__data.get() }
406 impl<'a, T> Drop for RwLockReadGuard<'a, T> {
408 unsafe { self.__lock.lock.read_unlock(); }
414 impl<'a, T> Drop for RwLockWriteGuard<'a, T> {
416 self.__lock.poison.done(&self.__poison);
417 unsafe { self.__lock.lock.write_unlock(); }
425 use rand::{self, Rng};
426 use sync::mpsc::channel;
428 use sync::{Arc, RwLock, StaticRwLock, RW_LOCK_INIT};
432 let l = RwLock::new(());
433 drop(l.read().unwrap());
434 drop(l.write().unwrap());
435 drop((l.read().unwrap(), l.read().unwrap()));
436 drop(l.write().unwrap());
441 static R: StaticRwLock = RW_LOCK_INIT;
442 drop(R.read().unwrap());
443 drop(R.write().unwrap());
444 drop((R.read().unwrap(), R.read().unwrap()));
445 drop(R.write().unwrap());
446 unsafe { R.destroy(); }
451 static R: StaticRwLock = RW_LOCK_INIT;
453 static M: uint = 1000;
455 let (tx, rx) = channel::<()>();
456 for _ in range(0, N) {
458 Thread::spawn(move|| {
459 let mut rng = rand::thread_rng();
460 for _ in range(0, M) {
461 if rng.gen_weighted_bool(N) {
462 drop(R.write().unwrap());
464 drop(R.read().unwrap());
472 unsafe { R.destroy(); }
476 fn test_rw_arc_poison_wr() {
477 let arc = Arc::new(RwLock::new(1i));
478 let arc2 = arc.clone();
479 let _: Result<uint, _> = Thread::scoped(move|| {
480 let _lock = arc2.write().unwrap();
483 assert!(arc.read().is_err());
487 fn test_rw_arc_poison_ww() {
488 let arc = Arc::new(RwLock::new(1i));
489 let arc2 = arc.clone();
490 let _: Result<uint, _> = Thread::scoped(move|| {
491 let _lock = arc2.write().unwrap();
494 assert!(arc.write().is_err());
498 fn test_rw_arc_no_poison_rr() {
499 let arc = Arc::new(RwLock::new(1i));
500 let arc2 = arc.clone();
501 let _: Result<uint, _> = Thread::scoped(move|| {
502 let _lock = arc2.read().unwrap();
505 let lock = arc.read().unwrap();
506 assert_eq!(*lock, 1);
509 fn test_rw_arc_no_poison_rw() {
510 let arc = Arc::new(RwLock::new(1i));
511 let arc2 = arc.clone();
512 let _: Result<uint, _> = Thread::scoped(move|| {
513 let _lock = arc2.read().unwrap();
516 let lock = arc.write().unwrap();
517 assert_eq!(*lock, 1);
522 let arc = Arc::new(RwLock::new(0i));
523 let arc2 = arc.clone();
524 let (tx, rx) = channel();
526 Thread::spawn(move|| {
527 let mut lock = arc2.write().unwrap();
528 for _ in range(0u, 10) {
534 tx.send(()).unwrap();
537 // Readers try to catch the writer in the act
538 let mut children = Vec::new();
539 for _ in range(0u, 5) {
540 let arc3 = arc.clone();
541 children.push(Thread::scoped(move|| {
542 let lock = arc3.read().unwrap();
547 // Wait for children to pass their asserts
548 for r in children.into_iter() {
549 assert!(r.join().is_ok());
552 // Wait for writer to finish
554 let lock = arc.read().unwrap();
555 assert_eq!(*lock, 10);
559 fn test_rw_arc_access_in_unwind() {
560 let arc = Arc::new(RwLock::new(1i));
561 let arc2 = arc.clone();
562 let _ = Thread::scoped(move|| -> () {
566 impl Drop for Unwinder {
568 let mut lock = self.i.write().unwrap();
572 let _u = Unwinder { i: arc2 };
575 let lock = arc.read().unwrap();
576 assert_eq!(*lock, 2);