Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement wait_while for condvar #356

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/sync/condvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ impl Condvar {
Ok(guard)
}

/// Blocks the current thread until this condition variable receives a notification and the
/// provided condition is false.
pub fn wait_while<'a, T, F>(
&self,
mut guard: MutexGuard<'a, T>,
mut condition: F,
) -> LockResult<MutexGuard<'a, T>>
where
F: FnMut(&mut T) -> bool,
{
while condition(&mut *guard) {
guard = self.wait(guard)?;
}

Ok(guard)
}

/// Waits on this condition variable for a notification, timing out after a
/// specified duration.
pub fn wait_timeout<'a, T>(
Expand Down
22 changes: 22 additions & 0 deletions tests/condvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,25 @@ impl Inc {
self.condvar.notify_all();
}
}

#[test]
fn wait_while() {
loom::model(|| {
let pair = Arc::new((Mutex::new(true), Condvar::new()));
let pair_2 = Arc::clone(&pair);

thread::spawn(move || {
let (lock, cvar) = &*pair_2;
let mut pending = lock.lock().unwrap();
*pending = false;
cvar.notify_one();
});

let (lock, cvar) = &*pair;
let guard = cvar
.wait_while(lock.lock().unwrap(), |pending| *pending)
.unwrap();

assert_eq!(*guard, false);
});
}