Skip to content

Commit

Permalink
Make RwLock::try_write try to obtain a write lock
Browse files Browse the repository at this point in the history
  • Loading branch information
hydhknn committed May 6, 2015
1 parent 7bd7163 commit 30b883b
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/libstd/sync/rwlock.rs
Expand Up @@ -232,7 +232,7 @@ impl<T: ?Sized> RwLock<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
if unsafe { self.inner.lock.try_read() } {
if unsafe { self.inner.lock.try_write() } {
Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data)))
} else {
Err(TryLockError::WouldBlock)
Expand Down Expand Up @@ -413,7 +413,7 @@ mod tests {
use rand::{self, Rng};
use sync::mpsc::channel;
use thread;
use sync::{Arc, RwLock, StaticRwLock, RW_LOCK_INIT};
use sync::{Arc, RwLock, StaticRwLock, TryLockError, RW_LOCK_INIT};

#[test]
fn smoke() {
Expand Down Expand Up @@ -577,4 +577,21 @@ mod tests {
let comp: &[i32] = &[4, 2, 5];
assert_eq!(&*rw.read().unwrap(), comp);
}

#[test]
fn test_rwlock_try_write() {
use mem::drop;

let lock = RwLock::new(0isize);
let read_guard = lock.read().unwrap();

let write_result = lock.try_write();
match write_result {
Err(TryLockError::WouldBlock) => (),
Ok(_) => assert!(false, "try_write should not succeed while read_guard is in scope"),
Err(_) => assert!(false, "unexpected error"),
}

drop(read_guard);
}
}

0 comments on commit 30b883b

Please sign in to comment.