diff --git a/sync/src/condvar.rs b/sync/src/condvar.rs new file mode 100644 index 0000000000..4a6e80d184 --- /dev/null +++ b/sync/src/condvar.rs @@ -0,0 +1,45 @@ +// Copyright 2018 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::fmt::{self, Debug}; +use std::sync::{Condvar as StdCondvar, MutexGuard}; + +/// A Condition Variable. +#[derive(Default)] +pub struct Condvar { + std: StdCondvar, +} + +impl Condvar { + /// Creates a new condvar that is ready to be waited on. + pub fn new() -> Condvar { + Condvar { + std: StdCondvar::new(), + } + } + + /// Waits on a condvar, blocking the current thread until it is notified. + pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> { + match self.std.wait(guard) { + Ok(guard) => guard, + Err(_) => panic!("condvar is poisoned"), + } + } + + /// Notifies one thread blocked by this condvar. + pub fn notify_one(&self) { + self.std.notify_one(); + } + + /// Notifies all threads blocked by this condvar. + pub fn notify_all(&self) { + self.std.notify_all(); + } +} + +impl Debug for Condvar { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.std, formatter) + } +} diff --git a/sync/src/lib.rs b/sync/src/lib.rs index c81ee0a13e..6fefbff06b 100644 --- a/sync/src/lib.rs +++ b/sync/src/lib.rs @@ -2,6 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +//! Sync primitive types whose methods panic rather than returning error in case of poison. +//! +//! The Mutex/Condvar type in this crates wraps the standard library versions and mirrors the same +//! methods, except that they panic where the standard library would return an Error. This API +//! codifies our error handling strategy around poisoned mutexes in crosvm. +//! +//! - Crosvm releases are built with panic=abort so poisoning never occurs. A panic while a mutex is +//! held (or ever) takes down the entire process. Thus we would like for code not to have to +//! consider the possibility of poison. +//! +//! - We could ask developers to always write `.lock().unwrap()` on a standard library mutex. +//! However, we would like to stigmatize the use of unwrap. It is confusing to permit unwrap but +//! only on mutex lock results. During code review it may not always be obvious whether a +//! particular unwrap is unwrapping a mutex lock result or a different error that should be +//! handled in a more principled way. +//! +//! Developers should feel free to use types defined in this crate anywhere in crosvm that they +//! would otherwise be using the corresponding types in std::sync. + +mod condvar; mod mutex; +pub use condvar::Condvar; pub use mutex::{Mutex, WouldBlock};