Skip to content

Commit

Permalink
Implement a fairer locking strategy for a new mutex type (#130)
Browse files Browse the repository at this point in the history
* Implement a fairer locking strategy.

* Merge out `FairMutex` into its own file.

* Add feature documentation

* Move increment after the check.

* Fix MSRV build

* Missed a couple
  • Loading branch information
notgull committed Oct 30, 2022
1 parent 0dfb21e commit ef6e68f
Show file tree
Hide file tree
Showing 4 changed files with 749 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ spin_mutex = ["mutex"]
# Enables `TicketMutex`.
ticket_mutex = ["mutex"]

# Enables `FairMutex`.
fair_mutex = ["mutex"]

# Enables the non-default ticket mutex implementation for `Mutex`.
use_ticket_mutex = ["mutex", "ticket_mutex"]

Expand Down
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@
//! - `lock_api` enables support for [`lock_api`](https://crates.io/crates/lock_api)
//!
//! - `ticket_mutex` uses a ticket lock for the implementation of `Mutex`
//!
//! - `fair_mutex` enables a fairer implementation of `Mutex` that uses eventual fairness to avoid
//! starvation
//!
//! - `std` enables support for thread yielding instead of spinning

Expand Down Expand Up @@ -192,3 +195,27 @@ pub mod lock_api {
pub type RwLockUpgradableReadGuard<'a, T> =
lock_api_crate::RwLockUpgradableReadGuard<'a, crate::RwLock<()>, T>;
}

/// In the event of an invalid operation, it's best to abort the current process.
#[cfg(feature = "fair_mutex")]
fn abort() -> !{
#[cfg(not(feature = "std"))]
{
// Panicking while panicking is defined by Rust to result in an abort.
struct Panic;

impl Drop for Panic {
fn drop(&mut self) {
panic!("aborting due to invalid operation");
}
}

let _panic = Panic;
panic!("aborting due to invalid operation");
}

#[cfg(feature = "std")]
{
std::process::abort();
}
}
7 changes: 7 additions & 0 deletions src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ pub mod ticket;
#[cfg_attr(docsrs, doc(cfg(feature = "ticket_mutex")))]
pub use self::ticket::{TicketMutex, TicketMutexGuard};

#[cfg(feature = "fair_mutex")]
#[cfg_attr(docsrs, doc(cfg(feature = "fair_mutex")))]
pub mod fair;
#[cfg(feature = "fair_mutex")]
#[cfg_attr(docsrs, doc(cfg(feature = "fair_mutex")))]
pub use self::fair::{FairMutex, FairMutexGuard, Starvation};

use core::{
fmt,
ops::{Deref, DerefMut},
Expand Down

0 comments on commit ef6e68f

Please sign in to comment.