Skip to content

Commit

Permalink
Implement wait_while for condvar
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasSte committed May 17, 2024
1 parent a7033ee commit b20d465
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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);
});
}

0 comments on commit b20d465

Please sign in to comment.