mirror of
https://github.com/bertptrs/tracing-mutex.git
synced 2025-12-27 21:40:32 +01:00
Compare commits
21 Commits
v0.2.1
...
0ae544a07a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ae544a07a | ||
| 4148d509bf | |||
| fc1593b76f | |||
| 8f19921e9e | |||
| 00420d6807 | |||
| 49b15bb6bd | |||
| 29c9daf53e | |||
|
|
8feedb09d2 | ||
| de9888a102 | |||
| 2d2e03eede | |||
| e9b577a0f5 | |||
| 5f6823394d | |||
|
|
61d19f866c | ||
| f78969ebf7 | |||
| 56b0604448 | |||
| 6e5516eaa7 | |||
| 764d3df454 | |||
|
|
e543860d8b | ||
|
|
ed04552af3 | ||
|
|
c5a506436c | ||
| 33cb6014a3 |
37
.github/workflows/ci.yml
vendored
37
.github/workflows/ci.yml
vendored
@@ -15,53 +15,34 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- "1.70" # minimum stable rust version
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rs/toolchain@v1
|
||||
- uses: dtolnay/rust-toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
components: rustfmt, clippy
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
# --all-targets ensures that we also build the benchmarks and tests already.
|
||||
args: --all-features --all-targets
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all-features
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: --all-features --all-targets -- -D warnings
|
||||
- run: cargo build --all-features --all-targets
|
||||
- run: cargo test --all-features
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --all-features --all-targets -- -D warnings
|
||||
|
||||
docs:
|
||||
name: Documentation build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rs/toolchain@v1
|
||||
- uses: dtolnay/rust-toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: nightly
|
||||
override: true
|
||||
|
||||
- name: Build documentation
|
||||
env:
|
||||
|
||||
16
CHANGELOG.md
16
CHANGELOG.md
@@ -6,6 +6,22 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- The minimum supported Rust version is now defined as 1.70. Previously it was undefined.
|
||||
- Wrappers for `std::sync` primitives can now be `const` constructed.
|
||||
- Add support for `std::sync::OnceLock`
|
||||
|
||||
### Breaking
|
||||
|
||||
- Update [`parking_lot`][parking_lot] dependency to `0.12`.
|
||||
- Restructured the crate to reduce typename verbosity. For details, see: #25.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Enforce that all internal mutex guards are `!Send`. They already should be according to other
|
||||
reasons, but this adds extra security through the type system.
|
||||
|
||||
## [0.2.1] - 2022-05-23
|
||||
|
||||
### Added
|
||||
|
||||
@@ -10,6 +10,7 @@ keywords = ["mutex", "rwlock", "once", "thread"]
|
||||
description = "Ensure deadlock-free mutexes by allocating in order, or else."
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/bertptrs/tracing-mutex"
|
||||
rust-version = "1.70"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# Build docs for all features so the documentation is more complete
|
||||
@@ -18,12 +19,11 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
lazy_static = "1"
|
||||
lock_api = { version = "0.4", optional = true }
|
||||
parking_lot = { version = "0.11", optional = true }
|
||||
parking_lot = { version = "0.12", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = "0.3"
|
||||
criterion = "0.5"
|
||||
rand = "0.8"
|
||||
|
||||
[[bench]]
|
||||
|
||||
11
README.md
11
README.md
@@ -23,10 +23,12 @@ tree out of it, and panics if your dependencies would create a cycle. It provide
|
||||
existing synchronization primitives with an identical API, and should be a drop-in replacement.
|
||||
|
||||
Inspired by [this blogpost][whileydave], which references a similar behaviour implemented by
|
||||
[Abseil][abseil-mutex] for their mutexes.
|
||||
[Abseil][abseil-mutex] for their mutexes. [This article goes into more depth on the exact
|
||||
implementation.][article]
|
||||
|
||||
[whileydave]: https://whileydave.com/2020/12/19/dynamic-cycle-detection-for-lock-ordering/
|
||||
[abseil-mutex]: https://abseil.io/docs/cpp/guides/synchronization
|
||||
[article]: https://bertptrs.nl/2022/06/23/deadlock-free-mutexes-and-directed-acyclic-graphs.html
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -42,9 +44,9 @@ Replacements for the synchronization primitives in `std::sync` can be found in t
|
||||
Support for other synchronization primitives is planned.
|
||||
|
||||
```rust
|
||||
use tracing_mutex::stdsync::TracingMutex;
|
||||
use tracing_mutex::stdsync::Mutex;
|
||||
|
||||
let some_mutex = TracingMutex::new(42);
|
||||
let some_mutex = Mutex::new(42);
|
||||
*some_mutex.lock().unwrap() += 1;
|
||||
println!("{:?}", some_mutex);
|
||||
```
|
||||
@@ -59,6 +61,9 @@ performance penalty in your production environment, this library also offers deb
|
||||
when debug assertions are enabled, and to `Mutex` when they are not. Similar helper types are
|
||||
available for other synchronization primitives.
|
||||
|
||||
The minimum supported Rust version is 1.70. Increasing this is not considered a breaking change, but
|
||||
will be avoided within semver-compatible releases if possible.
|
||||
|
||||
### Features
|
||||
|
||||
- Dependency-tracking wrappers for all locking primitives
|
||||
|
||||
@@ -7,7 +7,7 @@ use criterion::BenchmarkId;
|
||||
use criterion::Criterion;
|
||||
use criterion::Throughput;
|
||||
use rand::prelude::*;
|
||||
use tracing_mutex::stdsync::TracingMutex;
|
||||
use tracing_mutex::stdsync::tracing::Mutex as TracingMutex;
|
||||
|
||||
const SAMPLE_SIZES: [usize; 5] = [10, 30, 100, 300, 1000];
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
status = [
|
||||
'Rust project (1.70)',
|
||||
'Rust project (stable)',
|
||||
'Rust project (beta)',
|
||||
'Documentation build',
|
||||
|
||||
92
src/lib.rs
92
src/lib.rs
@@ -41,26 +41,23 @@
|
||||
//!
|
||||
//! These operations have been reasonably optimized, but the performance penalty may yet be too much
|
||||
//! for production use. In those cases, it may be beneficial to instead use debug-only versions
|
||||
//! (such as [`stdsync::DebugMutex`]) which evaluate to a tracing mutex when debug assertions are
|
||||
//! (such as [`stdsync::Mutex`]) which evaluate to a tracing mutex when debug assertions are
|
||||
//! enabled, and to the underlying mutex when they're not.
|
||||
//!
|
||||
//! [paper]: https://whileydave.com/publications/pk07_jea/
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
use std::cell::RefCell;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::ptr;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Once;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
#[cfg(feature = "lockapi")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "lockapi")))]
|
||||
pub use lock_api;
|
||||
@@ -79,11 +76,6 @@ pub mod lockapi;
|
||||
pub mod parkinglot;
|
||||
pub mod stdsync;
|
||||
|
||||
/// Counter for Mutex IDs. Atomic avoids the need for locking.
|
||||
///
|
||||
/// Should be part of the `MutexID` impl but static items are not yet a thing.
|
||||
static ID_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
thread_local! {
|
||||
/// Stack to track which locks are held
|
||||
///
|
||||
@@ -92,10 +84,6 @@ thread_local! {
|
||||
static HELD_LOCKS: RefCell<Vec<usize>> = RefCell::new(Vec::new());
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref DEPENDENCY_GRAPH: Mutex<DiGraph<usize>> = Default::default();
|
||||
}
|
||||
|
||||
/// Dedicated ID type for Mutexes
|
||||
///
|
||||
/// # Unstable
|
||||
@@ -114,6 +102,9 @@ impl MutexId {
|
||||
/// This function may panic when there are no more mutex IDs available. The number of mutex ids
|
||||
/// is `usize::MAX - 1` which should be plenty for most practical applications.
|
||||
pub fn new() -> Self {
|
||||
// Counter for Mutex IDs. Atomic avoids the need for locking.
|
||||
static ID_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
ID_SEQUENCE
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |id| id.checked_add(1))
|
||||
.map(Self)
|
||||
@@ -134,7 +125,10 @@ impl MutexId {
|
||||
/// This method panics if the new dependency would introduce a cycle.
|
||||
pub fn get_borrowed(&self) -> BorrowedMutex {
|
||||
self.mark_held();
|
||||
BorrowedMutex(self)
|
||||
BorrowedMutex {
|
||||
id: self,
|
||||
_not_send: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark this lock as held for the purposes of dependency tracking.
|
||||
@@ -204,17 +198,13 @@ impl Drop for MutexId {
|
||||
///
|
||||
/// This type can be largely replaced once std::lazy gets stabilized.
|
||||
struct LazyMutexId {
|
||||
inner: UnsafeCell<MaybeUninit<MutexId>>,
|
||||
setter: Once,
|
||||
_marker: PhantomData<MutexId>,
|
||||
inner: OnceLock<MutexId>,
|
||||
}
|
||||
|
||||
impl LazyMutexId {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: UnsafeCell::new(MaybeUninit::uninit()),
|
||||
setter: Once::new(),
|
||||
_marker: PhantomData,
|
||||
inner: OnceLock::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,51 +221,30 @@ impl Default for LazyMutexId {
|
||||
}
|
||||
}
|
||||
|
||||
/// Safety: the UnsafeCell is guaranteed to only be accessed mutably from a `Once`.
|
||||
unsafe impl Sync for LazyMutexId {}
|
||||
|
||||
impl Deref for LazyMutexId {
|
||||
type Target = MutexId;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.setter.call_once(|| {
|
||||
// Safety: this function is only called once, so only one mutable reference should exist
|
||||
// at a time.
|
||||
unsafe {
|
||||
*self.inner.get() = MaybeUninit::new(MutexId::new());
|
||||
}
|
||||
});
|
||||
|
||||
// Safety: after the above Once runs, there are no longer any mutable references, so we can
|
||||
// hand this out safely.
|
||||
//
|
||||
// Explanation of this monstrosity:
|
||||
//
|
||||
// - Get a pointer to the data from the UnsafeCell
|
||||
// - Dereference that to get a reference to the underlying MaybeUninit
|
||||
// - Use as_ptr on MaybeUninit to get a pointer to the initialized MutexID
|
||||
// - Dereference the pointer to turn in into a reference as intended.
|
||||
//
|
||||
// This should get slightly nicer once `maybe_uninit_extra` is stabilized.
|
||||
unsafe { &*((*self.inner.get()).as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LazyMutexId {
|
||||
fn drop(&mut self) {
|
||||
if self.setter.is_completed() {
|
||||
// We have a valid mutex ID and need to drop it
|
||||
|
||||
// Safety: we know that this pointer is valid because the initializer has successfully run.
|
||||
let mutex_id = unsafe { ptr::read((*self.inner.get()).as_ptr()) };
|
||||
|
||||
drop(mutex_id);
|
||||
}
|
||||
self.inner.get_or_init(MutexId::new)
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed mutex ID
|
||||
///
|
||||
/// This type should be used as part of a mutex guard wrapper. It can be acquired through
|
||||
/// [`MutexId::get_borrowed`] and will automatically mark the mutex as not borrowed when it is
|
||||
/// dropped.
|
||||
///
|
||||
/// This type intentionally is [`!Send`](std::marker::Send) because the ownership tracking is based
|
||||
/// on a thread-local stack which doesn't work if a guard gets released in a different thread from
|
||||
/// where they're acquired.
|
||||
#[derive(Debug)]
|
||||
struct BorrowedMutex<'a>(&'a MutexId);
|
||||
struct BorrowedMutex<'a> {
|
||||
/// Reference to the mutex we're borrowing from
|
||||
id: &'a MutexId,
|
||||
/// This value serves no purpose but to make the type [`!Send`](std::marker::Send)
|
||||
_not_send: PhantomData<MutexGuard<'static, ()>>,
|
||||
}
|
||||
|
||||
/// Drop a lock held by the current thread.
|
||||
///
|
||||
@@ -286,13 +255,16 @@ struct BorrowedMutex<'a>(&'a MutexId);
|
||||
impl<'a> Drop for BorrowedMutex<'a> {
|
||||
fn drop(&mut self) {
|
||||
// Safety: the only way to get a BorrowedMutex is by locking the mutex.
|
||||
unsafe { self.0.mark_released() };
|
||||
unsafe { self.id.mark_released() };
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a reference to the current dependency graph
|
||||
fn get_dependency_graph() -> impl DerefMut<Target = DiGraph<usize>> {
|
||||
static DEPENDENCY_GRAPH: OnceLock<Mutex<DiGraph<usize>>> = OnceLock::new();
|
||||
|
||||
DEPENDENCY_GRAPH
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
//! Wrapper types and type aliases for tracing [`parking_lot`] mutexes.
|
||||
//!
|
||||
//! This module provides type aliases that use the [`lockapi`][crate::lockapi] module to provide
|
||||
//! tracing variants of the `parking_lot` primitives. Each of the `TracingX` type aliases wraps an
|
||||
//! `X` in the `parkint_lot` api with dependency tracking, and a `DebugX` will refer to a `TracingX`
|
||||
//! when `debug_assertions` are enabled and to `X` when they're not. This can be used to aid
|
||||
//! debugging in development while enjoying maximum performance in production.
|
||||
//! tracing variants of the `parking_lot` primitives. The [`tracing`] module contains type aliases
|
||||
//! that use dependency tracking, while the main `parking_lot` primitives are reexported as [`raw`].
|
||||
//!
|
||||
//! This main module imports from [`tracing`] when `debug_assertions` are enabled, and from [`raw`]
|
||||
//! when they're not. Note that primitives for which no tracing wrapper exists are not imported into
|
||||
//! the main module.
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! ```
|
||||
//! # use std::sync::Arc;
|
||||
//! # use std::thread;
|
||||
//! # use lock_api::Mutex;
|
||||
//! # use tracing_mutex::parkinglot::TracingMutex;
|
||||
//! let mutex = Arc::new(TracingMutex::new(0));
|
||||
//! use tracing_mutex::parkinglot::Mutex;
|
||||
//! let mutex = Arc::new(Mutex::new(0));
|
||||
//!
|
||||
//! let handles: Vec<_> = (0..10).map(|_| {
|
||||
//! let mutex = Arc::clone(&mutex);
|
||||
@@ -37,191 +38,130 @@
|
||||
//! In addition, the mutex guards returned by the tracing wrappers are `!Send`, regardless of
|
||||
//! whether `parking_lot` is configured to have `Send` mutex guards. This is a limitation of the
|
||||
//! current bookkeeping system.
|
||||
use parking_lot::Once;
|
||||
use parking_lot::OnceState;
|
||||
|
||||
use crate::lockapi::TracingWrapper;
|
||||
use crate::LazyMutexId;
|
||||
pub use parking_lot as raw;
|
||||
|
||||
macro_rules! debug_variant {
|
||||
($debug_name:ident, $tracing_name:ident, $normal_name:ty) => {
|
||||
type $tracing_name = TracingWrapper<$normal_name>;
|
||||
#[cfg(debug_assertions)]
|
||||
pub use tracing::{
|
||||
FairMutex, FairMutexGuard, MappedFairMutexGuard, MappedMutexGuard, MappedReentrantMutexGuard,
|
||||
MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, MutexGuard, Once, OnceState,
|
||||
ReentrantMutex, ReentrantMutexGuard, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard,
|
||||
RwLockWriteGuard,
|
||||
};
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
type $debug_name = TracingWrapper<$normal_name>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
type $debug_name = $normal_name;
|
||||
};
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub use parking_lot::{
|
||||
FairMutex, FairMutexGuard, MappedFairMutexGuard, MappedMutexGuard, MappedReentrantMutexGuard,
|
||||
MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, MutexGuard, Once, OnceState,
|
||||
ReentrantMutex, ReentrantMutexGuard, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard,
|
||||
RwLockWriteGuard,
|
||||
};
|
||||
|
||||
debug_variant!(
|
||||
DebugRawFairMutex,
|
||||
TracingRawFairMutex,
|
||||
parking_lot::RawFairMutex
|
||||
);
|
||||
debug_variant!(DebugRawMutex, TracingRawMutex, parking_lot::RawMutex);
|
||||
debug_variant!(DebugRawRwLock, TracingRawRwLock, parking_lot::RawRwLock);
|
||||
/// Dependency tracing wrappers for [`parking_lot`].
|
||||
pub mod tracing {
|
||||
pub use parking_lot::OnceState;
|
||||
|
||||
/// Dependency tracking fair mutex. See: [`parking_lot::FairMutex`].
|
||||
pub type TracingFairMutex<T> = lock_api::Mutex<TracingRawFairMutex, T>;
|
||||
/// Mutex guard for [`TracingFairMutex`].
|
||||
pub type TracingFairMutexGuard<'a, T> = lock_api::MutexGuard<'a, TracingRawFairMutex, T>;
|
||||
/// RAII guard for `TracingFairMutexGuard::map`.
|
||||
pub type TracingMappedFairMutexGuard<'a, T> =
|
||||
lock_api::MappedMutexGuard<'a, TracingRawFairMutex, T>;
|
||||
/// Debug-only dependency tracking fair mutex.
|
||||
///
|
||||
/// If debug assertions are enabled this resolves to [`TracingFairMutex`] and to
|
||||
/// [`parking_lot::FairMutex`] otherwise.
|
||||
pub type DebugFairMutex<T> = lock_api::Mutex<DebugRawFairMutex, T>;
|
||||
/// Mutex guard for [`DebugFairMutex`].
|
||||
pub type DebugFairMutexGuard<'a, T> = lock_api::MutexGuard<'a, DebugRawFairMutex, T>;
|
||||
/// RAII guard for `DebugFairMutexGuard::map`.
|
||||
pub type DebugMappedFairMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, DebugRawFairMutex, T>;
|
||||
use crate::lockapi::TracingWrapper;
|
||||
use crate::LazyMutexId;
|
||||
|
||||
/// Dependency tracking mutex. See: [`parking_lot::Mutex`].
|
||||
pub type TracingMutex<T> = lock_api::Mutex<TracingRawMutex, T>;
|
||||
/// Mutex guard for [`TracingMutex`].
|
||||
pub type TracingMutexGuard<'a, T> = lock_api::MutexGuard<'a, TracingRawMutex, T>;
|
||||
/// RAII guard for `TracingMutexGuard::map`.
|
||||
pub type TracingMappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, TracingRawMutex, T>;
|
||||
/// Debug-only dependency tracking mutex.
|
||||
///
|
||||
/// If debug assertions are enabled this resolves to [`TracingMutex`] and to [`parking_lot::Mutex`]
|
||||
/// otherwise.
|
||||
pub type DebugMutex<T> = lock_api::Mutex<DebugRawMutex, T>;
|
||||
/// Mutex guard for [`DebugMutex`].
|
||||
pub type DebugMutexGuard<'a, T> = lock_api::MutexGuard<'a, DebugRawMutex, T>;
|
||||
/// RAII guard for `TracingMutexGuard::map`.
|
||||
pub type DebugMappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, DebugRawMutex, T>;
|
||||
type RawFairMutex = TracingWrapper<parking_lot::RawFairMutex>;
|
||||
type RawMutex = TracingWrapper<parking_lot::RawMutex>;
|
||||
type RawRwLock = TracingWrapper<parking_lot::RawRwLock>;
|
||||
|
||||
/// Dependency tracking reentrant mutex. See: [`parking_lot::ReentrantMutex`].
|
||||
///
|
||||
/// **Note:** due to the way dependencies are tracked, this mutex can only be acquired directly
|
||||
/// after itself. Acquiring any other mutex in between introduces a dependency cycle, and will
|
||||
/// therefore be rejected.
|
||||
pub type TracingReentrantMutex<T> =
|
||||
lock_api::ReentrantMutex<TracingWrapper<parking_lot::RawMutex>, parking_lot::RawThreadId, T>;
|
||||
/// Mutex guard for [`TracingReentrantMutex`].
|
||||
pub type TracingReentrantMutexGuard<'a, T> = lock_api::ReentrantMutexGuard<
|
||||
'a,
|
||||
TracingWrapper<parking_lot::RawMutex>,
|
||||
parking_lot::RawThreadId,
|
||||
T,
|
||||
>;
|
||||
/// RAII guard for `TracingReentrantMutexGuard::map`.
|
||||
pub type TracingMappedReentrantMutexGuard<'a, T> =
|
||||
lock_api::MappedReentrantMutexGuard<'a, TracingRawMutex, parking_lot::RawThreadId, T>;
|
||||
/// Dependency tracking fair mutex. See: [`parking_lot::FairMutex`].
|
||||
pub type FairMutex<T> = lock_api::Mutex<RawFairMutex, T>;
|
||||
/// Mutex guard for [`FairMutex`].
|
||||
pub type FairMutexGuard<'a, T> = lock_api::MutexGuard<'a, RawFairMutex, T>;
|
||||
/// RAII guard for [`FairMutexGuard::map`].
|
||||
pub type MappedFairMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawFairMutex, T>;
|
||||
|
||||
/// Debug-only dependency tracking reentrant mutex.
|
||||
///
|
||||
/// If debug assertions are enabled this resolves to [`TracingReentrantMutex`] and to
|
||||
/// [`parking_lot::ReentrantMutex`] otherwise.
|
||||
pub type DebugReentrantMutex<T> =
|
||||
lock_api::ReentrantMutex<DebugRawMutex, parking_lot::RawThreadId, T>;
|
||||
/// Mutex guard for [`DebugReentrantMutex`].
|
||||
pub type DebugReentrantMutexGuard<'a, T> =
|
||||
lock_api::ReentrantMutexGuard<'a, DebugRawMutex, parking_lot::RawThreadId, T>;
|
||||
/// RAII guard for `DebugReentrantMutexGuard::map`.
|
||||
pub type DebugMappedReentrantMutexGuard<'a, T> =
|
||||
lock_api::MappedReentrantMutexGuard<'a, DebugRawMutex, parking_lot::RawThreadId, T>;
|
||||
/// Dependency tracking mutex. See: [`parking_lot::Mutex`].
|
||||
pub type Mutex<T> = lock_api::Mutex<RawMutex, T>;
|
||||
/// Mutex guard for [`Mutex`].
|
||||
pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>;
|
||||
/// RAII guard for [`MutexGuard::map`].
|
||||
pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>;
|
||||
|
||||
/// Dependency tracking RwLock. See: [`parking_lot::RwLock`].
|
||||
pub type TracingRwLock<T> = lock_api::RwLock<TracingRawRwLock, T>;
|
||||
/// Read guard for [`TracingRwLock`].
|
||||
pub type TracingRwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, TracingRawRwLock, T>;
|
||||
/// Upgradable Read guard for [`TracingRwLock`].
|
||||
pub type TracingRwLockUpgradableReadGuard<'a, T> =
|
||||
lock_api::RwLockUpgradableReadGuard<'a, TracingRawRwLock, T>;
|
||||
/// Write guard for [`TracingRwLock`].
|
||||
pub type TracingRwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, TracingRawRwLock, T>;
|
||||
/// RAII guard for `TracingRwLockReadGuard::map`.
|
||||
pub type TracingMappedRwLockReadGuard<'a, T> =
|
||||
lock_api::MappedRwLockReadGuard<'a, TracingRawRwLock, T>;
|
||||
/// RAII guard for `TracingRwLockWriteGuard::map`.
|
||||
pub type TracingMappedRwLockWriteGuard<'a, T> =
|
||||
lock_api::MappedRwLockWriteGuard<'a, TracingRawRwLock, T>;
|
||||
/// Dependency tracking reentrant mutex. See: [`parking_lot::ReentrantMutex`].
|
||||
///
|
||||
/// **Note:** due to the way dependencies are tracked, this mutex can only be acquired directly
|
||||
/// after itself. Acquiring any other mutex in between introduces a dependency cycle, and will
|
||||
/// therefore be rejected.
|
||||
pub type ReentrantMutex<T> = lock_api::ReentrantMutex<RawMutex, parking_lot::RawThreadId, T>;
|
||||
/// Mutex guard for [`ReentrantMutex`].
|
||||
pub type ReentrantMutexGuard<'a, T> =
|
||||
lock_api::ReentrantMutexGuard<'a, RawMutex, parking_lot::RawThreadId, T>;
|
||||
/// RAII guard for `ReentrantMutexGuard::map`.
|
||||
pub type MappedReentrantMutexGuard<'a, T> =
|
||||
lock_api::MappedReentrantMutexGuard<'a, RawMutex, parking_lot::RawThreadId, T>;
|
||||
|
||||
/// Debug-only dependency tracking RwLock.
|
||||
///
|
||||
/// If debug assertions are enabled this resolved to [`TracingRwLock`] and to
|
||||
/// [`parking_lot::RwLock`] otherwise.
|
||||
pub type DebugRwLock<T> = lock_api::RwLock<DebugRawRwLock, T>;
|
||||
/// Read guard for [`TracingRwLock`].
|
||||
pub type DebugRwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, DebugRawRwLock, T>;
|
||||
/// Upgradable Read guard for [`TracingRwLock`].
|
||||
pub type DebugRwLockUpgradableReadGuard<'a, T> =
|
||||
lock_api::RwLockUpgradableReadGuard<'a, DebugRawRwLock, T>;
|
||||
/// Write guard for [`TracingRwLock`].
|
||||
pub type DebugRwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, DebugRawRwLock, T>;
|
||||
/// RAII guard for `DebugRwLockReadGuard::map`.
|
||||
pub type DebugMappedRwLockReadGuard<'a, T> = lock_api::MappedRwLockReadGuard<'a, DebugRawRwLock, T>;
|
||||
/// RAII guard for `DebugRwLockWriteGuard::map`.
|
||||
pub type DebugMappedRwLockWriteGuard<'a, T> =
|
||||
lock_api::MappedRwLockWriteGuard<'a, DebugRawRwLock, T>;
|
||||
/// Dependency tracking RwLock. See: [`parking_lot::RwLock`].
|
||||
pub type RwLock<T> = lock_api::RwLock<RawRwLock, T>;
|
||||
/// Read guard for [`RwLock`].
|
||||
pub type RwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, RawRwLock, T>;
|
||||
/// Upgradable Read guard for [`RwLock`].
|
||||
pub type RwLockUpgradableReadGuard<'a, T> =
|
||||
lock_api::RwLockUpgradableReadGuard<'a, RawRwLock, T>;
|
||||
/// Write guard for [`RwLock`].
|
||||
pub type RwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, RawRwLock, T>;
|
||||
/// RAII guard for `RwLockReadGuard::map`.
|
||||
pub type MappedRwLockReadGuard<'a, T> = lock_api::MappedRwLockReadGuard<'a, RawRwLock, T>;
|
||||
/// RAII guard for `RwLockWriteGuard::map`.
|
||||
pub type MappedRwLockWriteGuard<'a, T> = lock_api::MappedRwLockWriteGuard<'a, RawRwLock, T>;
|
||||
|
||||
/// A dependency-tracking wrapper for [`parking_lot::Once`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TracingOnce {
|
||||
inner: Once,
|
||||
id: LazyMutexId,
|
||||
}
|
||||
/// A dependency-tracking wrapper for [`parking_lot::Once`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Once {
|
||||
inner: parking_lot::Once,
|
||||
id: LazyMutexId,
|
||||
}
|
||||
|
||||
impl TracingOnce {
|
||||
/// Create a new `TracingOnce` value.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: Once::new(),
|
||||
id: LazyMutexId::new(),
|
||||
impl Once {
|
||||
/// Create a new `Once` value.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: parking_lot::Once::new(),
|
||||
id: LazyMutexId::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the current state of this `Once`.
|
||||
pub fn state(&self) -> OnceState {
|
||||
self.inner.state()
|
||||
}
|
||||
|
||||
/// This call is considered as "locking this `Once`" and it participates in dependency
|
||||
/// tracking as such.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method will panic if `f` panics, poisoning this `Once`. In addition, this function
|
||||
/// panics when the lock acquisition order is determined to be inconsistent.
|
||||
pub fn call_once(&self, f: impl FnOnce()) {
|
||||
let _borrow = self.id.get_borrowed();
|
||||
self.inner.call_once(f);
|
||||
}
|
||||
|
||||
/// Performs the given initialization routine once and only once.
|
||||
///
|
||||
/// This method is identical to [`Once::call_once`] except it ignores poisoning.
|
||||
pub fn call_once_force(&self, f: impl FnOnce(OnceState)) {
|
||||
let _borrow = self.id.get_borrowed();
|
||||
self.inner.call_once_force(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the current state of this `Once`.
|
||||
pub fn state(&self) -> OnceState {
|
||||
self.inner.state()
|
||||
}
|
||||
|
||||
///
|
||||
/// This call is considered as "locking this `TracingOnce`" and it participates in dependency
|
||||
/// tracking as such.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method will panic if `f` panics, poisoning this `Once`. In addition, this function
|
||||
/// panics when the lock acquisition order is determined to be inconsistent.
|
||||
pub fn call_once(&self, f: impl FnOnce()) {
|
||||
let _borrow = self.id.get_borrowed();
|
||||
self.inner.call_once(f);
|
||||
}
|
||||
|
||||
/// Performs the given initialization routine once and only once.
|
||||
///
|
||||
/// This method is identical to [`TracingOnce::call_once`] except it ignores poisoning.
|
||||
pub fn call_once_force(&self, f: impl FnOnce(OnceState)) {
|
||||
let _borrow = self.id.get_borrowed();
|
||||
self.inner.call_once_force(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Debug-only `Once`.
|
||||
///
|
||||
/// If debug assertions are enabled this resolves to [`TracingOnce`] and to [`parking_lot::Once`]
|
||||
/// otherwise.
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugOnce = TracingOnce;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugOnce = Once;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use super::*;
|
||||
use super::tracing;
|
||||
|
||||
#[test]
|
||||
fn test_mutex_usage() {
|
||||
let mutex = Arc::new(TracingMutex::new(()));
|
||||
let mutex = Arc::new(tracing::Mutex::new(()));
|
||||
let local_lock = mutex.lock();
|
||||
drop(local_lock);
|
||||
|
||||
@@ -236,9 +176,9 @@ mod tests {
|
||||
#[should_panic]
|
||||
fn test_mutex_conflict() {
|
||||
let mutexes = [
|
||||
TracingMutex::new(()),
|
||||
TracingMutex::new(()),
|
||||
TracingMutex::new(()),
|
||||
tracing::Mutex::new(()),
|
||||
tracing::Mutex::new(()),
|
||||
tracing::Mutex::new(()),
|
||||
];
|
||||
|
||||
for i in 0..3 {
|
||||
@@ -249,7 +189,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rwlock_usage() {
|
||||
let lock = Arc::new(TracingRwLock::new(()));
|
||||
let lock = Arc::new(tracing::RwLock::new(()));
|
||||
let lock2 = Arc::clone(&lock);
|
||||
|
||||
let _read_lock = lock.read();
|
||||
@@ -264,19 +204,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rwlock_upgradable_read_usage() {
|
||||
let lock = TracingRwLock::new(());
|
||||
let lock = tracing::RwLock::new(());
|
||||
|
||||
// Should be able to acquire an upgradable read lock.
|
||||
let upgradable_guard: TracingRwLockUpgradableReadGuard<'_, _> = lock.upgradable_read();
|
||||
let upgradable_guard: tracing::RwLockUpgradableReadGuard<'_, _> = lock.upgradable_read();
|
||||
|
||||
// Should be able to upgrade the guard.
|
||||
let _write_guard: TracingRwLockWriteGuard<'_, _> =
|
||||
TracingRwLockUpgradableReadGuard::upgrade(upgradable_guard);
|
||||
let _write_guard: tracing::RwLockWriteGuard<'_, _> =
|
||||
tracing::RwLockUpgradableReadGuard::upgrade(upgradable_guard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_once_usage() {
|
||||
let once = Arc::new(TracingOnce::new());
|
||||
let once = Arc::new(tracing::Once::new());
|
||||
let once_clone = once.clone();
|
||||
|
||||
assert!(!once_clone.state().done());
|
||||
|
||||
1240
src/stdsync.rs
1240
src/stdsync.rs
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user