]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/rwlock.rs
auto merge of #21132 : sfackler/rust/wait_timeout, r=alexcrichton
[rust.git] / src / libstd / sync / rwlock.rs
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.
4 //
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.
10
11 use prelude::v1::*;
12
13 use cell::UnsafeCell;
14 use marker;
15 use ops::{Deref, DerefMut};
16 use sync::poison::{self, LockResult, TryLockError, TryLockResult};
17 use sys_common::rwlock as sys;
18
19 /// A reader-writer lock
20 ///
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).
25 ///
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.
31 ///
32 /// # Poisoning
33 ///
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.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use std::sync::RwLock;
43 ///
44 /// let lock = RwLock::new(5i);
45 ///
46 /// // many reader locks can be held at once
47 /// {
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
53 ///
54 /// // only one write lock may be held, however
55 /// {
56 ///     let mut w = lock.write().unwrap();
57 ///     *w += 1;
58 ///     assert_eq!(*w, 6);
59 /// } // write lock is dropped here
60 /// ```
61 #[stable]
62 pub struct RwLock<T> {
63     inner: Box<StaticRwLock>,
64     data: UnsafeCell<T>,
65 }
66
67 unsafe impl<T:'static+Send> Send for RwLock<T> {}
68 unsafe impl<T> Sync for RwLock<T> {}
69
70 /// Structure representing a statically allocated RwLock.
71 ///
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.
75 ///
76 /// # Example
77 ///
78 /// ```
79 /// use std::sync::{StaticRwLock, RW_LOCK_INIT};
80 ///
81 /// static LOCK: StaticRwLock = RW_LOCK_INIT;
82 ///
83 /// {
84 ///     let _g = LOCK.read().unwrap();
85 ///     // ... shared read access
86 /// }
87 /// {
88 ///     let _g = LOCK.write().unwrap();
89 ///     // ... exclusive write access
90 /// }
91 /// unsafe { LOCK.destroy() } // free all resources
92 /// ```
93 #[unstable = "may be merged with RwLock in the future"]
94 pub struct StaticRwLock {
95     lock: sys::RWLock,
96     poison: poison::Flag,
97 }
98
99 unsafe impl Send for StaticRwLock {}
100 unsafe impl Sync for StaticRwLock {}
101
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,
107 };
108
109 /// RAII structure used to release the shared read access of a lock when
110 /// dropped.
111 #[must_use]
112 #[stable]
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,
118 }
119
120 /// RAII structure used to release the shared read access of a lock when
121 /// dropped.
122 #[must_use]
123 #[stable]
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>,
128 }
129
130 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
131 impl<'a, T> !marker::Send for RwLockReadGuard<'a, T> {}
132
133 /// RAII structure used to release the exclusive write access of a lock when
134 /// dropped.
135 #[must_use]
136 #[stable]
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,
143 }
144
145 /// RAII structure used to release the exclusive write access of a lock when
146 /// dropped.
147 #[must_use]
148 #[stable]
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,
154 }
155
156 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
157 impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {}
158
159 impl<T: Send + Sync> RwLock<T> {
160     /// Creates a new instance of an RwLock which is unlocked and read to go.
161     #[stable]
162     pub fn new(t: T) -> RwLock<T> {
163         RwLock { inner: box RW_LOCK_INIT, data: UnsafeCell::new(t) }
164     }
165
166     /// Locks this rwlock with shared read access, blocking the current thread
167     /// until it can be acquired.
168     ///
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.
174     ///
175     /// Returns an RAII guard which will release this thread's shared access
176     /// once it is dropped.
177     ///
178     /// # Failure
179     ///
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.
183     #[inline]
184     #[stable]
185     pub fn read(&self) -> LockResult<RwLockReadGuard<T>> {
186         unsafe { self.inner.lock.read() }
187         RwLockReadGuard::new(&*self.inner, &self.data)
188     }
189
190     /// Attempt to acquire this lock with shared read access.
191     ///
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.
198     ///
199     /// # Failure
200     ///
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
204     /// acquired.
205     #[inline]
206     #[stable]
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)))
210         } else {
211             Err(TryLockError::WouldBlock)
212         }
213     }
214
215     /// Lock this rwlock with exclusive write access, blocking the current
216     /// thread until it can be acquired.
217     ///
218     /// This function will not return while other writers or other readers
219     /// currently have access to the lock.
220     ///
221     /// Returns an RAII guard which will drop the write access of this rwlock
222     /// when dropped.
223     ///
224     /// # Failure
225     ///
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.
229     #[inline]
230     #[stable]
231     pub fn write(&self) -> LockResult<RwLockWriteGuard<T>> {
232         unsafe { self.inner.lock.write() }
233         RwLockWriteGuard::new(&*self.inner, &self.data)
234     }
235
236     /// Attempt to lock this rwlock with exclusive write access.
237     ///
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
240     /// returned.
241     ///
242     /// # Failure
243     ///
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
247     /// acquired.
248     #[inline]
249     #[stable]
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)))
253         } else {
254             Err(TryLockError::WouldBlock)
255         }
256     }
257 }
258
259 #[unsafe_destructor]
260 #[stable]
261 impl<T> Drop for RwLock<T> {
262     fn drop(&mut self) {
263         unsafe { self.inner.lock.destroy() }
264     }
265 }
266
267 struct Dummy(UnsafeCell<()>);
268 unsafe impl Sync for Dummy {}
269 static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
270
271 impl StaticRwLock {
272     /// Locks this rwlock with shared read access, blocking the current thread
273     /// until it can be acquired.
274     ///
275     /// See `RwLock::read`.
276     #[inline]
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)
281     }
282
283     /// Attempt to acquire this lock with shared read access.
284     ///
285     /// See `RwLock::try_read`.
286     #[inline]
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)))
292         } else {
293             Err(TryLockError::WouldBlock)
294         }
295     }
296
297     /// Lock this rwlock with exclusive write access, blocking the current
298     /// thread until it can be acquired.
299     ///
300     /// See `RwLock::write`.
301     #[inline]
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)
306     }
307
308     /// Attempt to lock this rwlock with exclusive write access.
309     ///
310     /// See `RwLock::try_write`.
311     #[inline]
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)))
317         } else {
318             Err(TryLockError::WouldBlock)
319         }
320     }
321
322     /// Deallocate all resources associated with this static lock.
323     ///
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
327     /// all platforms.
328     #[unstable = "may be merged with RwLock in the future"]
329     pub unsafe fn destroy(&'static self) {
330         self.lock.destroy()
331     }
332 }
333
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(), |_| {
339             RwLockReadGuard {
340                 __lock: lock,
341                 __data: data,
342                 __marker: marker::NoSend,
343             }
344         })
345     }
346
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(), |_| {
351             RwLockReadGuard {
352                 __lock: lock,
353                 __data: data,
354             }
355         })
356     }
357 }
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| {
363             RwLockWriteGuard {
364                 __lock: lock,
365                 __data: data,
366                 __poison: guard,
367                 __marker: marker::NoSend,
368             }
369         })
370     }
371
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| {
376             RwLockWriteGuard {
377                 __lock: lock,
378                 __data: data,
379                 __poison: guard,
380             }
381         })
382     }
383 }
384
385 #[stable]
386 impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> {
387     type Target = T;
388
389     fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
390 }
391 #[stable]
392 impl<'rwlock, T> Deref for RwLockWriteGuard<'rwlock, T> {
393     type Target = T;
394
395     fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
396 }
397 #[stable]
398 impl<'rwlock, T> DerefMut for RwLockWriteGuard<'rwlock, T> {
399     fn deref_mut(&mut self) -> &mut T {
400         unsafe { &mut *self.__data.get() }
401     }
402 }
403
404 #[unsafe_destructor]
405 #[stable]
406 impl<'a, T> Drop for RwLockReadGuard<'a, T> {
407     fn drop(&mut self) {
408         unsafe { self.__lock.lock.read_unlock(); }
409     }
410 }
411
412 #[unsafe_destructor]
413 #[stable]
414 impl<'a, T> Drop for RwLockWriteGuard<'a, T> {
415     fn drop(&mut self) {
416         self.__lock.poison.done(&self.__poison);
417         unsafe { self.__lock.lock.write_unlock(); }
418     }
419 }
420
421 #[cfg(test)]
422 mod tests {
423     use prelude::v1::*;
424
425     use rand::{self, Rng};
426     use sync::mpsc::channel;
427     use thread::Thread;
428     use sync::{Arc, RwLock, StaticRwLock, RW_LOCK_INIT};
429
430     #[test]
431     fn smoke() {
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());
437     }
438
439     #[test]
440     fn static_smoke() {
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(); }
447     }
448
449     #[test]
450     fn frob() {
451         static R: StaticRwLock = RW_LOCK_INIT;
452         static N: uint = 10;
453         static M: uint = 1000;
454
455         let (tx, rx) = channel::<()>();
456         for _ in range(0, N) {
457             let tx = tx.clone();
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());
463                     } else {
464                         drop(R.read().unwrap());
465                     }
466                 }
467                 drop(tx);
468             });
469         }
470         drop(tx);
471         let _ = rx.recv();
472         unsafe { R.destroy(); }
473     }
474
475     #[test]
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();
481             panic!();
482         }).join();
483         assert!(arc.read().is_err());
484     }
485
486     #[test]
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();
492             panic!();
493         }).join();
494         assert!(arc.write().is_err());
495     }
496
497     #[test]
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();
503             panic!();
504         }).join();
505         let lock = arc.read().unwrap();
506         assert_eq!(*lock, 1);
507     }
508     #[test]
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();
514             panic!()
515         }).join();
516         let lock = arc.write().unwrap();
517         assert_eq!(*lock, 1);
518     }
519
520     #[test]
521     fn test_rw_arc() {
522         let arc = Arc::new(RwLock::new(0i));
523         let arc2 = arc.clone();
524         let (tx, rx) = channel();
525
526         Thread::spawn(move|| {
527             let mut lock = arc2.write().unwrap();
528             for _ in range(0u, 10) {
529                 let tmp = *lock;
530                 *lock = -1;
531                 Thread::yield_now();
532                 *lock = tmp + 1;
533             }
534             tx.send(()).unwrap();
535         });
536
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();
543                 assert!(*lock >= 0);
544             }));
545         }
546
547         // Wait for children to pass their asserts
548         for r in children.into_iter() {
549             assert!(r.join().is_ok());
550         }
551
552         // Wait for writer to finish
553         rx.recv().unwrap();
554         let lock = arc.read().unwrap();
555         assert_eq!(*lock, 10);
556     }
557
558     #[test]
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|| -> () {
563             struct Unwinder {
564                 i: Arc<RwLock<int>>,
565             }
566             impl Drop for Unwinder {
567                 fn drop(&mut self) {
568                     let mut lock = self.i.write().unwrap();
569                     *lock += 1;
570                 }
571             }
572             let _u = Unwinder { i: arc2 };
573             panic!();
574         }).join();
575         let lock = arc.read().unwrap();
576         assert_eq!(*lock, 2);
577     }
578 }