Skip to content

Commit 30b883b

Browse files
committed
Make RwLock::try_write try to obtain a write lock
1 parent 7bd7163 commit 30b883b

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/libstd/sync/rwlock.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ impl<T: ?Sized> RwLock<T> {
232232
#[inline]
233233
#[stable(feature = "rust1", since = "1.0.0")]
234234
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
235-
if unsafe { self.inner.lock.try_read() } {
235+
if unsafe { self.inner.lock.try_write() } {
236236
Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data)))
237237
} else {
238238
Err(TryLockError::WouldBlock)
@@ -413,7 +413,7 @@ mod tests {
413413
use rand::{self, Rng};
414414
use sync::mpsc::channel;
415415
use thread;
416-
use sync::{Arc, RwLock, StaticRwLock, RW_LOCK_INIT};
416+
use sync::{Arc, RwLock, StaticRwLock, TryLockError, RW_LOCK_INIT};
417417

418418
#[test]
419419
fn smoke() {
@@ -577,4 +577,21 @@ mod tests {
577577
let comp: &[i32] = &[4, 2, 5];
578578
assert_eq!(&*rw.read().unwrap(), comp);
579579
}
580+
581+
#[test]
582+
fn test_rwlock_try_write() {
583+
use mem::drop;
584+
585+
let lock = RwLock::new(0isize);
586+
let read_guard = lock.read().unwrap();
587+
588+
let write_result = lock.try_write();
589+
match write_result {
590+
Err(TryLockError::WouldBlock) => (),
591+
Ok(_) => assert!(false, "try_write should not succeed while read_guard is in scope"),
592+
Err(_) => assert!(false, "unexpected error"),
593+
}
594+
595+
drop(read_guard);
596+
}
580597
}

0 commit comments

Comments
 (0)