mirror of
https://github.com/bertptrs/tracing-mutex.git
synced 2025-12-25 20:50:32 +01:00
Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43df59ac1c | ||
| 1fe44d0a05 | |||
| c9083c8bc1 | |||
|
|
d8c559fd3f | ||
| a8e8af6351 | |||
| 068303d81d | |||
| 6be3e05cab | |||
| 909e934572 | |||
|
|
0ae544a07a | ||
| 4148d509bf | |||
| fc1593b76f | |||
| 8f19921e9e | |||
| 00420d6807 | |||
| 49b15bb6bd | |||
| 29c9daf53e | |||
|
|
8feedb09d2 | ||
| de9888a102 | |||
| 2d2e03eede | |||
| e9b577a0f5 | |||
| 5f6823394d | |||
|
|
61d19f866c | ||
| f78969ebf7 | |||
| 56b0604448 | |||
| 6e5516eaa7 | |||
| 764d3df454 | |||
|
|
e543860d8b | ||
|
|
ed04552af3 | ||
|
|
c5a506436c | ||
| 33cb6014a3 | |||
| 5232bac582 | |||
|
|
6472f4b807 | ||
| 6afe7b1c48 | |||
| 9238ef53ee | |||
|
|
c08addff7d | ||
|
|
c1ce9df8ad | ||
| 312eaa8649 | |||
|
|
1f7e6921aa | ||
| f7048f265f | |||
| 64e56fdb86 | |||
|
|
8e3278fdd2 | ||
| 9ea993e737 | |||
| 062850fc3e | |||
| 0d2622d5c6 | |||
| d1417e0b0c | |||
| fcc64e2cef | |||
| fd0d05307c |
44
.github/workflows/ci.yml
vendored
44
.github/workflows/ci.yml
vendored
@@ -2,48 +2,50 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- staging
|
||||
- trying
|
||||
pull_request:
|
||||
|
||||
name: Continuous integration
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
tests:
|
||||
name: Rust project
|
||||
runs-on: ubuntu-latest
|
||||
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
|
||||
- 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
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all-features
|
||||
docs:
|
||||
name: Documentation build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
- uses: dtolnay/rust-toolchain@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: --all-features --all-targets -- -D warnings
|
||||
toolchain: nightly
|
||||
|
||||
- name: Build documentation
|
||||
env:
|
||||
# Build the docs like docs.rs builds it
|
||||
RUSTDOCFLAGS: --cfg docsrs
|
||||
run: cargo doc --all-features
|
||||
|
||||
45
CHANGELOG.md
45
CHANGELOG.md
@@ -6,7 +6,45 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.2.0]
|
||||
## [0.3.0] - 2023-09-09
|
||||
|
||||
### 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`
|
||||
- Added backtraces of mutex allocations to the cycle report. Capturing backtraces does incur some
|
||||
overhead, this can be mitigated by disabling the `backtraces` feature which is enabled by default.
|
||||
|
||||
### Breaking
|
||||
|
||||
- Update [`parking_lot`][parking_lot] dependency to `0.12`.
|
||||
- Restructured the crate to reduce typename verbosity. Wrapper names now match the name of the
|
||||
primitive they wrap. Specific always/debug tracing versions have now moved to separate modules.
|
||||
For example, `tracing_mutex::stdsync::TracingMutex` is now
|
||||
`tracing_mutex::stdsync::tracing::Mutex`, and `tracing_mutex::stdsync::DebugMutex` is now called
|
||||
`tracing_mutex::stdsync::Mutex`. This hopefully reduces the visual noise while reading code that
|
||||
uses this in practice. Unwrapped primitives are reexported under `tracing_mutex::stdsync::raw` for
|
||||
convenience.
|
||||
|
||||
### 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
|
||||
|
||||
- Build [docs.rs] documentation with all features enabled for completeness.
|
||||
- Add support for `std::sync::Condvar`
|
||||
|
||||
### Fixed
|
||||
|
||||
- The `parkinglot` module is now correctly enabled by the `parkinglot` feature rather than the
|
||||
`lockapi` feature.
|
||||
|
||||
## [0.2.0] - 2022-05-07
|
||||
|
||||
### Added
|
||||
- Generic support for wrapping mutexes that implement the traits provided by the
|
||||
@@ -55,11 +93,14 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
Initial release.
|
||||
|
||||
[Unreleased]: https://github.com/bertptrs/tracing-mutex/compare/v0.2.0...HEAD
|
||||
[Unreleased]: https://github.com/bertptrs/tracing-mutex/compare/v0.3.0...HEAD
|
||||
[0.3.0]: https://github.com/bertptrs/tracing-mutex/compare/v0.2.1...v0.3.0
|
||||
[0.2.1]: https://github.com/bertptrs/tracing-mutex/compare/v0.2.0...v0.2.1
|
||||
[0.2.0]: https://github.com/bertptrs/tracing-mutex/compare/v0.1.2...v0.2.0
|
||||
[0.1.2]: https://github.com/bertptrs/tracing-mutex/compare/v0.1.1...v0.1.2
|
||||
[0.1.1]: https://github.com/bertptrs/tracing-mutex/compare/v0.1.0...v0.1.1
|
||||
[0.1.0]: https://github.com/bertptrs/tracing-mutex/releases/tag/v0.1.0
|
||||
|
||||
[docs.rs]: https://docs.rs/tracing-mutex/latest/tracing_mutex/
|
||||
[lock_api]: https://docs.rs/lock_api/
|
||||
[parking_lot]: https://docs.rs/parking_lot/
|
||||
|
||||
16
Cargo.toml
16
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tracing-mutex"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
authors = ["Bert Peters <bert@bertptrs.nl>"]
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
@@ -10,14 +10,20 @@ 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
|
||||
all-features = true
|
||||
# Set custom cfg so we can enable docs.rs magic
|
||||
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]]
|
||||
@@ -25,6 +31,8 @@ name = "mutex"
|
||||
harness = false
|
||||
|
||||
[features]
|
||||
default = ["backtraces"]
|
||||
backtraces = []
|
||||
# Feature names do not match crate names pending namespaced features.
|
||||
lockapi = ["lock_api"]
|
||||
parkinglot = ["parking_lot", "lockapi"]
|
||||
|
||||
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2022 Bert Peters
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright © 2021 Bert Peters
|
||||
Copyright © 2022 Bert Peters
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the “Software”), to deal in the Software without restriction,
|
||||
|
||||
26
README.md
26
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
|
||||
|
||||
@@ -34,7 +36,7 @@ Add this dependency to your `Cargo.lock` file like any other:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tracing-mutex = "0.1"
|
||||
tracing-mutex = "0.2"
|
||||
```
|
||||
|
||||
Then use the locks provided by this library instead of the ones you would use otherwise.
|
||||
@@ -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,12 +61,26 @@ 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
|
||||
- Optional opt-out for release mode code
|
||||
- Support for primitives from:
|
||||
- `std::sync`
|
||||
- `parking_lot`
|
||||
- Any library that implements the `lock_api` traits
|
||||
|
||||
## Future improvements
|
||||
|
||||
- Improve performance in lock tracing
|
||||
- Optional logging to make debugging easier
|
||||
- Better and configurable error handling when detecting cyclic dependencies
|
||||
- Support for other locking libraries, such as `parking_lot`
|
||||
- Support for other locking libraries
|
||||
- Support for async locking libraries
|
||||
- Support for `Send` mutex guards
|
||||
|
||||
**Note:** `parking_lot` has already began work on its own deadlock detection mechanism, which works
|
||||
in a different way. Both can be complimentary.
|
||||
|
||||
@@ -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];
|
||||
|
||||
|
||||
6
bors.toml
Normal file
6
bors.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
status = [
|
||||
'Rust project (1.70)',
|
||||
'Rust project (stable)',
|
||||
'Rust project (beta)',
|
||||
'Documentation build',
|
||||
]
|
||||
26
examples/mutex_cycle.rs
Normal file
26
examples/mutex_cycle.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Show what a crash looks like
|
||||
//!
|
||||
//! This shows what a traceback of a cycle detection looks like. It is expected to crash.
|
||||
use tracing_mutex::stdsync::Mutex;
|
||||
|
||||
fn main() {
|
||||
let a = Mutex::new(());
|
||||
let b = Mutex::new(());
|
||||
let c = Mutex::new(());
|
||||
|
||||
// Create an edge from a to b
|
||||
{
|
||||
let _a = a.lock();
|
||||
let _b = b.lock();
|
||||
}
|
||||
|
||||
// Create an edge from b to c
|
||||
{
|
||||
let _b = b.lock();
|
||||
let _c = c.lock();
|
||||
}
|
||||
|
||||
// Now crash by trying to add an edge from c to a
|
||||
let _c = c.lock();
|
||||
let _a = a.lock(); // This line will crash
|
||||
}
|
||||
130
src/graph.rs
130
src/graph.rs
@@ -1,4 +1,5 @@
|
||||
use std::cell::Cell;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
@@ -19,23 +20,24 @@ type Order = usize;
|
||||
/// visibly changed.
|
||||
///
|
||||
/// [paper]: https://whileydave.com/publications/pk07_jea/
|
||||
#[derive(Default, Debug)]
|
||||
pub struct DiGraph<V>
|
||||
#[derive(Debug)]
|
||||
pub struct DiGraph<V, E>
|
||||
where
|
||||
V: Eq + Hash + Copy,
|
||||
{
|
||||
nodes: HashMap<V, Node<V>>,
|
||||
/// Next topological sort order
|
||||
next_ord: Order,
|
||||
nodes: HashMap<V, Node<V, E>>,
|
||||
// Instead of reordering the orders in the graph whenever a node is deleted, we maintain a list
|
||||
// of unused ids that can be handed out later again.
|
||||
unused_order: Vec<Order>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Node<V>
|
||||
struct Node<V, E>
|
||||
where
|
||||
V: Eq + Hash + Clone,
|
||||
{
|
||||
in_edges: HashSet<V>,
|
||||
out_edges: HashSet<V>,
|
||||
out_edges: HashMap<V, E>,
|
||||
// The "Ord" field is a Cell to ensure we can update it in an immutable context.
|
||||
// `std::collections::HashMap` doesn't let you have multiple mutable references to elements, but
|
||||
// this way we can use immutable references and still update `ord`. This saves quite a few
|
||||
@@ -43,7 +45,7 @@ where
|
||||
ord: Cell<Order>,
|
||||
}
|
||||
|
||||
impl<V> DiGraph<V>
|
||||
impl<V, E> DiGraph<V, E>
|
||||
where
|
||||
V: Eq + Hash + Copy,
|
||||
{
|
||||
@@ -54,12 +56,18 @@ where
|
||||
/// the node in the topological order.
|
||||
///
|
||||
/// New nodes are appended to the end of the topological order when added.
|
||||
fn add_node(&mut self, n: V) -> (&mut HashSet<V>, &mut HashSet<V>, Order) {
|
||||
let next_ord = &mut self.next_ord;
|
||||
fn add_node(&mut self, n: V) -> (&mut HashSet<V>, &mut HashMap<V, E>, Order) {
|
||||
// need to compute next id before the call to entry() to avoid duplicate borrow of nodes
|
||||
let fallback_id = self.nodes.len();
|
||||
|
||||
let node = self.nodes.entry(n).or_insert_with(|| {
|
||||
let order = *next_ord;
|
||||
*next_ord = next_ord.checked_add(1).expect("Topological order overflow");
|
||||
let order = if let Some(id) = self.unused_order.pop() {
|
||||
// Reuse discarded ordering entry
|
||||
id
|
||||
} else {
|
||||
// Allocate new order id
|
||||
fallback_id
|
||||
};
|
||||
|
||||
Node {
|
||||
ord: Cell::new(order),
|
||||
@@ -77,9 +85,12 @@ where
|
||||
Some(Node {
|
||||
out_edges,
|
||||
in_edges,
|
||||
..
|
||||
ord,
|
||||
}) => {
|
||||
out_edges.into_iter().for_each(|m| {
|
||||
// Return ordering to the pool of unused ones
|
||||
self.unused_order.push(ord.get());
|
||||
|
||||
out_edges.into_keys().for_each(|m| {
|
||||
self.nodes.get_mut(&m).unwrap().in_edges.remove(&n);
|
||||
});
|
||||
|
||||
@@ -96,18 +107,29 @@ where
|
||||
///
|
||||
/// Nodes, both from and to, are created as needed when creating new edges. If the new edge
|
||||
/// would introduce a cycle, the edge is rejected and `false` is returned.
|
||||
pub(crate) fn add_edge(&mut self, x: V, y: V) -> bool {
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the edge would introduce the cycle, the underlying graph is not modified and a list of
|
||||
/// all the edge data in the would-be cycle is returned instead.
|
||||
pub(crate) fn add_edge(&mut self, x: V, y: V, e: impl FnOnce() -> E) -> Result<(), Vec<E>>
|
||||
where
|
||||
E: Clone,
|
||||
{
|
||||
if x == y {
|
||||
// self-edges are always considered cycles
|
||||
return false;
|
||||
return Err(Vec::new());
|
||||
}
|
||||
|
||||
let (_, out_edges, ub) = self.add_node(x);
|
||||
|
||||
if !out_edges.insert(y) {
|
||||
match out_edges.entry(y) {
|
||||
Entry::Occupied(_) => {
|
||||
// Edge already exists, nothing to be done
|
||||
return true;
|
||||
return Ok(());
|
||||
}
|
||||
Entry::Vacant(entry) => entry.insert(e()),
|
||||
};
|
||||
|
||||
let (in_edges, _, lb) = self.add_node(y);
|
||||
|
||||
@@ -119,7 +141,7 @@ where
|
||||
let mut delta_f = Vec::new();
|
||||
let mut delta_b = Vec::new();
|
||||
|
||||
if !self.dfs_f(&self.nodes[&y], ub, &mut visited, &mut delta_f) {
|
||||
if let Err(cycle) = self.dfs_f(&self.nodes[&y], ub, &mut visited, &mut delta_f) {
|
||||
// This edge introduces a cycle, so we want to reject it and remove it from the
|
||||
// graph again to keep the "does not contain cycles" invariant.
|
||||
|
||||
@@ -129,7 +151,7 @@ where
|
||||
self.nodes.get_mut(&x).map(|node| node.out_edges.remove(&y));
|
||||
|
||||
// No edge was added
|
||||
return false;
|
||||
return Err(cycle);
|
||||
}
|
||||
|
||||
// No need to check as we should've found the cycle on the forward pass
|
||||
@@ -141,44 +163,49 @@ where
|
||||
self.reorder(delta_f, delta_b);
|
||||
}
|
||||
|
||||
true
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forwards depth-first-search
|
||||
fn dfs_f<'a>(
|
||||
&'a self,
|
||||
n: &'a Node<V>,
|
||||
n: &'a Node<V, E>,
|
||||
ub: Order,
|
||||
visited: &mut HashSet<V>,
|
||||
delta_f: &mut Vec<&'a Node<V>>,
|
||||
) -> bool {
|
||||
delta_f: &mut Vec<&'a Node<V, E>>,
|
||||
) -> Result<(), Vec<E>>
|
||||
where
|
||||
E: Clone,
|
||||
{
|
||||
delta_f.push(n);
|
||||
|
||||
n.out_edges.iter().all(|w| {
|
||||
for (w, e) in &n.out_edges {
|
||||
let node = &self.nodes[w];
|
||||
let ord = node.ord.get();
|
||||
|
||||
if ord == ub {
|
||||
// Found a cycle
|
||||
false
|
||||
return Err(vec![e.clone()]);
|
||||
} else if !visited.contains(w) && ord < ub {
|
||||
// Need to check recursively
|
||||
visited.insert(*w);
|
||||
self.dfs_f(node, ub, visited, delta_f)
|
||||
} else {
|
||||
// Already seen this one or not interesting
|
||||
true
|
||||
if let Err(mut chain) = self.dfs_f(node, ub, visited, delta_f) {
|
||||
chain.push(e.clone());
|
||||
return Err(chain);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Backwards depth-first-search
|
||||
fn dfs_b<'a>(
|
||||
&'a self,
|
||||
n: &'a Node<V>,
|
||||
n: &'a Node<V, E>,
|
||||
lb: Order,
|
||||
visited: &mut HashSet<V>,
|
||||
delta_b: &mut Vec<&'a Node<V>>,
|
||||
delta_b: &mut Vec<&'a Node<V, E>>,
|
||||
) {
|
||||
delta_b.push(n);
|
||||
|
||||
@@ -192,7 +219,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn reorder(&self, mut delta_f: Vec<&Node<V>>, mut delta_b: Vec<&Node<V>>) {
|
||||
fn reorder(&self, mut delta_f: Vec<&Node<V, E>>, mut delta_b: Vec<&Node<V, E>>) {
|
||||
self.sort(&mut delta_f);
|
||||
self.sort(&mut delta_b);
|
||||
|
||||
@@ -213,12 +240,25 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn sort(&self, ids: &mut [&Node<V>]) {
|
||||
fn sort(&self, ids: &mut [&Node<V, E>]) {
|
||||
// Can use unstable sort because mutex ids should not be equal
|
||||
ids.sort_unstable_by_key(|v| &v.ord);
|
||||
}
|
||||
}
|
||||
|
||||
// Manual `Default` impl as derive causes unnecessarily strong bounds.
|
||||
impl<V, E> Default for DiGraph<V, E>
|
||||
where
|
||||
V: Eq + Hash + Copy,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
nodes: Default::default(),
|
||||
unused_order: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rand::seq::SliceRandom;
|
||||
@@ -226,12 +266,14 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
fn nop() {}
|
||||
|
||||
#[test]
|
||||
fn test_no_self_cycle() {
|
||||
// Regression test for https://github.com/bertptrs/tracing-mutex/issues/7
|
||||
let mut graph = DiGraph::default();
|
||||
|
||||
assert!(!graph.add_edge(1, 1));
|
||||
assert!(graph.add_edge(1, 1, nop).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -239,16 +281,16 @@ mod tests {
|
||||
let mut graph = DiGraph::default();
|
||||
|
||||
// Add some safe edges
|
||||
assert!(graph.add_edge(0, 1));
|
||||
assert!(graph.add_edge(1, 2));
|
||||
assert!(graph.add_edge(2, 3));
|
||||
assert!(graph.add_edge(4, 2));
|
||||
assert!(graph.add_edge(0, 1, nop).is_ok());
|
||||
assert!(graph.add_edge(1, 2, nop).is_ok());
|
||||
assert!(graph.add_edge(2, 3, nop).is_ok());
|
||||
assert!(graph.add_edge(4, 2, nop).is_ok());
|
||||
|
||||
// Try to add an edge that introduces a cycle
|
||||
assert!(!graph.add_edge(3, 1));
|
||||
assert!(graph.add_edge(3, 1, nop).is_err());
|
||||
|
||||
// Add an edge that should reorder 0 to be after 4
|
||||
assert!(graph.add_edge(4, 0));
|
||||
assert!(graph.add_edge(4, 0, nop).is_ok());
|
||||
}
|
||||
|
||||
/// Fuzz the DiGraph implementation by adding a bunch of valid edges.
|
||||
@@ -256,7 +298,7 @@ mod tests {
|
||||
/// This test generates all possible forward edges in a 100-node graph consisting of natural
|
||||
/// numbers, shuffles them, then adds them to the graph. This will always be a valid directed,
|
||||
/// acyclic graph because there is a trivial order (the natural numbers) but because the edges
|
||||
/// are added in a random order the DiGraph will still occassionally need to reorder nodes.
|
||||
/// are added in a random order the DiGraph will still occasionally need to reorder nodes.
|
||||
#[test]
|
||||
fn fuzz_digraph() {
|
||||
// Note: this fuzzer is quadratic in the number of nodes, so this cannot be too large or it
|
||||
@@ -277,7 +319,7 @@ mod tests {
|
||||
let mut graph = DiGraph::default();
|
||||
|
||||
for (x, y) in edges {
|
||||
assert!(graph.add_edge(x, y));
|
||||
assert!(graph.add_edge(x, y, nop).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
150
src/lib.rs
150
src/lib.rs
@@ -18,8 +18,23 @@
|
||||
//! # Structure
|
||||
//!
|
||||
//! Each module in this crate exposes wrappers for a specific base-mutex with dependency trakcing
|
||||
//! added. For now, that is limited to [`stdsync`] which provides wrappers for the base locks in the
|
||||
//! standard library. More back-ends may be added as features in the future.
|
||||
//! added. This includes [`stdsync`] which provides wrappers for the base locks in the standard
|
||||
//! library, and more depending on enabled compile-time features. More back-ends may be added as
|
||||
//! features in the future.
|
||||
//!
|
||||
//! # Feature flags
|
||||
//!
|
||||
//! `tracing-mutex` uses feature flags to reduce the impact of this crate on both your compile time
|
||||
//! and runtime overhead. Below are the available flags. Modules are annotated with the features
|
||||
//! they require.
|
||||
//!
|
||||
//! - `backtraces`: Enables capturing backtraces of mutex dependencies, to make it easier to
|
||||
//! determine what sequence of events would trigger a deadlock. This is enabled by default, but if
|
||||
//! the performance overhead is unaccceptable, it can be disabled by disabling default features.
|
||||
//!
|
||||
//! - `lockapi`: Enables the wrapper lock for [`lock_api`][lock_api] locks
|
||||
//!
|
||||
//! - `parkinglot`: Enables wrapper types for [`parking_lot`][parking_lot] mutexes
|
||||
//!
|
||||
//! # Performance considerations
|
||||
//!
|
||||
@@ -41,44 +56,50 @@
|
||||
//!
|
||||
//! 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.
|
||||
//!
|
||||
//! For ease of debugging, this crate will, by default, capture a backtrace when establishing a new
|
||||
//! dependency between two mutexes. This has an additional overhead of over 60%. If this additional
|
||||
//! debugging aid is not required, it can be disabled by disabling default features.
|
||||
//!
|
||||
//! [paper]: https://whileydave.com/publications/pk07_jea/
|
||||
//! [lock_api]: https://docs.rs/lock_api/0.4/lock_api/index.html
|
||||
//! [parking_lot]: https://docs.rs/parking_lot/0.12.1/parking_lot/
|
||||
#![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;
|
||||
#[cfg(feature = "parkinglot")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "parkinglot")))]
|
||||
pub use parking_lot;
|
||||
use reporting::Dep;
|
||||
use reporting::Reportable;
|
||||
|
||||
use crate::graph::DiGraph;
|
||||
|
||||
mod graph;
|
||||
#[cfg(feature = "lockapi")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "lockapi")))]
|
||||
pub mod lockapi;
|
||||
#[cfg(feature = "lockapi")]
|
||||
#[cfg(feature = "parkinglot")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "parkinglot")))]
|
||||
pub mod parkinglot;
|
||||
mod reporting;
|
||||
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
|
||||
///
|
||||
@@ -87,10 +108,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
|
||||
@@ -109,6 +126,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)
|
||||
@@ -129,7 +149,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.
|
||||
@@ -138,19 +161,18 @@ impl MutexId {
|
||||
///
|
||||
/// This method panics if the new dependency would introduce a cycle.
|
||||
pub fn mark_held(&self) {
|
||||
let creates_cycle = HELD_LOCKS.with(|locks| {
|
||||
let opt_cycle = HELD_LOCKS.with(|locks| {
|
||||
if let Some(&previous) = locks.borrow().last() {
|
||||
let mut graph = get_dependency_graph();
|
||||
|
||||
!graph.add_edge(previous, self.value())
|
||||
graph.add_edge(previous, self.value(), Dep::capture).err()
|
||||
} else {
|
||||
false
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
if creates_cycle {
|
||||
// Panic without holding the lock to avoid needlessly poisoning it
|
||||
panic!("Mutex order graph should not have cycles");
|
||||
if let Some(cycle) = opt_cycle {
|
||||
panic!("{}", Dep::panic_message(&cycle))
|
||||
}
|
||||
|
||||
HELD_LOCKS.with(|locks| locks.borrow_mut().push(self.value()));
|
||||
@@ -199,17 +221,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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,51 +244,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.
|
||||
///
|
||||
@@ -281,13 +278,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>> {
|
||||
fn get_dependency_graph() -> impl DerefMut<Target = DiGraph<usize, Dep>> {
|
||||
static DEPENDENCY_GRAPH: OnceLock<Mutex<DiGraph<usize, Dep>>> = OnceLock::new();
|
||||
|
||||
DEPENDENCY_GRAPH
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
@@ -315,11 +315,11 @@ mod tests {
|
||||
let c = LazyMutexId::new();
|
||||
|
||||
let mut graph = get_dependency_graph();
|
||||
assert!(graph.add_edge(a.value(), b.value()));
|
||||
assert!(graph.add_edge(b.value(), c.value()));
|
||||
assert!(graph.add_edge(a.value(), b.value(), Dep::capture).is_ok());
|
||||
assert!(graph.add_edge(b.value(), c.value(), Dep::capture).is_ok());
|
||||
|
||||
// Creating an edge c → a should fail as it introduces a cycle.
|
||||
assert!(!graph.add_edge(c.value(), a.value()));
|
||||
assert!(graph.add_edge(c.value(), a.value(), Dep::capture).is_err());
|
||||
|
||||
// Drop graph handle so we can drop vertices without deadlocking
|
||||
drop(graph);
|
||||
@@ -327,7 +327,9 @@ mod tests {
|
||||
drop(b);
|
||||
|
||||
// If b's destructor correctly ran correctly we can now add an edge from c to a.
|
||||
assert!(get_dependency_graph().add_edge(c.value(), a.value()));
|
||||
assert!(get_dependency_graph()
|
||||
.add_edge(c.value(), a.value(), Dep::capture)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
/// Test creating a cycle, then panicking.
|
||||
|
||||
@@ -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,141 +38,89 @@
|
||||
//! 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;
|
||||
|
||||
pub use parking_lot as raw;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub use tracing::{
|
||||
FairMutex, FairMutexGuard, MappedFairMutexGuard, MappedMutexGuard, MappedReentrantMutexGuard,
|
||||
MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, MutexGuard, Once, OnceState,
|
||||
ReentrantMutex, ReentrantMutexGuard, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard,
|
||||
RwLockWriteGuard,
|
||||
};
|
||||
|
||||
#[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,
|
||||
};
|
||||
|
||||
/// Dependency tracing wrappers for [`parking_lot`].
|
||||
pub mod tracing {
|
||||
pub use parking_lot::OnceState;
|
||||
|
||||
use crate::lockapi::TracingWrapper;
|
||||
use crate::LazyMutexId;
|
||||
|
||||
macro_rules! debug_variant {
|
||||
($debug_name:ident, $tracing_name:ident, $normal_name:ty) => {
|
||||
type $tracing_name = TracingWrapper<$normal_name>;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
type $debug_name = TracingWrapper<$normal_name>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
type $debug_name = $normal_name;
|
||||
};
|
||||
}
|
||||
|
||||
debug_variant!(
|
||||
DebugRawFairMutex,
|
||||
TracingRawFairMutex,
|
||||
parking_lot::RawFairMutex
|
||||
);
|
||||
debug_variant!(DebugRawMutex, TracingRawMutex, parking_lot::RawMutex);
|
||||
debug_variant!(DebugRawRwLock, TracingRawRwLock, parking_lot::RawRwLock);
|
||||
type RawFairMutex = TracingWrapper<parking_lot::RawFairMutex>;
|
||||
type RawMutex = TracingWrapper<parking_lot::RawMutex>;
|
||||
type RawRwLock = TracingWrapper<parking_lot::RawRwLock>;
|
||||
|
||||
/// 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>;
|
||||
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>;
|
||||
|
||||
/// 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>;
|
||||
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 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>;
|
||||
|
||||
/// 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>;
|
||||
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>;
|
||||
|
||||
/// 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>;
|
||||
|
||||
/// 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>;
|
||||
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,
|
||||
pub struct Once {
|
||||
inner: parking_lot::Once,
|
||||
id: LazyMutexId,
|
||||
}
|
||||
|
||||
impl TracingOnce {
|
||||
/// Create a new `TracingOnce` value.
|
||||
impl Once {
|
||||
/// Create a new `Once` value.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: Once::new(),
|
||||
inner: parking_lot::Once::new(),
|
||||
id: LazyMutexId::new(),
|
||||
}
|
||||
}
|
||||
@@ -181,8 +130,7 @@ impl TracingOnce {
|
||||
self.inner.state()
|
||||
}
|
||||
|
||||
///
|
||||
/// This call is considered as "locking this `TracingOnce`" and it participates in dependency
|
||||
/// This call is considered as "locking this `Once`" and it participates in dependency
|
||||
/// tracking as such.
|
||||
///
|
||||
/// # Panics
|
||||
@@ -194,34 +142,26 @@ impl TracingOnce {
|
||||
self.inner.call_once(f);
|
||||
}
|
||||
|
||||
/// Performs the given initialization routeine once and only once.
|
||||
/// Performs the given initialization routine once and only once.
|
||||
///
|
||||
/// This method is identical to [`TracingOnce::call_once`] except it ignores poisining.
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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());
|
||||
|
||||
64
src/reporting.rs
Normal file
64
src/reporting.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
//! Cycle reporting primitives
|
||||
//!
|
||||
//! This module exposes [`Dep`], which resolves to either something that tracks dependencies or to
|
||||
//! something that doesn't. It should only be assumed to implement the [`Reportable`] trait.
|
||||
use std::backtrace::Backtrace;
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "backtraces")]
|
||||
pub type Dep = MutexDep<Arc<Backtrace>>;
|
||||
#[cfg(not(feature = "backtraces"))]
|
||||
pub type Dep = MutexDep<()>;
|
||||
|
||||
// Base message to be reported when cycle is detected
|
||||
const BASE_MESSAGE: &str = "Found cycle in mutex dependency graph:";
|
||||
|
||||
pub trait Reportable: Clone {
|
||||
/// Capture the current state
|
||||
fn capture() -> Self;
|
||||
|
||||
/// Format a trace of state for human readable consumption.
|
||||
fn panic_message(trace: &[Self]) -> Cow<'static, str>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MutexDep<T>(T);
|
||||
|
||||
/// Use a unit as tracing data: no tracing.
|
||||
///
|
||||
/// This should have no runtime overhead for capturing traces and should therefore be cheap enough
|
||||
/// for most purposes.
|
||||
impl Reportable for MutexDep<()> {
|
||||
fn capture() -> Self {
|
||||
Self(())
|
||||
}
|
||||
|
||||
fn panic_message(_trace: &[Self]) -> Cow<'static, str> {
|
||||
Cow::Borrowed(BASE_MESSAGE)
|
||||
}
|
||||
}
|
||||
|
||||
/// Use a full backtrace as tracing data
|
||||
///
|
||||
/// Capture the entire backtrace which may be expensive. This implementation does not force capture
|
||||
/// in the event that backtraces are disabled at runtime, so the exact overhead can still be
|
||||
/// controlled a little.
|
||||
///
|
||||
/// N.B. the [`Backtrace`] needs to be wrapped in an Arc as backtraces are not [`Clone`].
|
||||
impl Reportable for MutexDep<Arc<Backtrace>> {
|
||||
fn capture() -> Self {
|
||||
Self(Arc::new(Backtrace::capture()))
|
||||
}
|
||||
|
||||
fn panic_message(trace: &[Self]) -> Cow<'static, str> {
|
||||
let mut message = format!("{BASE_MESSAGE}\n");
|
||||
|
||||
for entry in trace {
|
||||
let _ = writeln!(message, "{}", entry.0);
|
||||
}
|
||||
|
||||
message.into()
|
||||
}
|
||||
}
|
||||
432
src/stdsync.rs
432
src/stdsync.rs
@@ -1,102 +1,69 @@
|
||||
//! Tracing mutex wrappers for locks found in `std::sync`.
|
||||
//!
|
||||
//! This module provides wrappers for `std::sync` primitives with exactly the same API and
|
||||
//! functionality as their counterparts, with the exception that their acquisition order is
|
||||
//! tracked.
|
||||
//! functionality as their counterparts, with the exception that their acquisition order is tracked.
|
||||
//!
|
||||
//! Dedicated wrappers that provide the dependency tracing can be found in the [`tracing`] module.
|
||||
//! The original primitives are available from [`std::sync`], imported as [`raw`] for convenience.
|
||||
//!
|
||||
//! If debug assertions are enabled, this module imports the primitives from [`tracing`], otherwise
|
||||
//! it will import from [`raw`].
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use tracing_mutex::stdsync::TracingMutex;
|
||||
//! # use tracing_mutex::stdsync::TracingRwLock;
|
||||
//! let mutex = TracingMutex::new(());
|
||||
//! # use tracing_mutex::stdsync::tracing::Mutex;
|
||||
//! # use tracing_mutex::stdsync::tracing::RwLock;
|
||||
//! let mutex = Mutex::new(());
|
||||
//! mutex.lock().unwrap();
|
||||
//!
|
||||
//! let rwlock = TracingRwLock::new(());
|
||||
//! let rwlock = RwLock::new(());
|
||||
//! rwlock.read().unwrap();
|
||||
//! ```
|
||||
pub use std::sync as raw;
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub use std::sync::{
|
||||
Condvar, Mutex, MutexGuard, Once, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard,
|
||||
};
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub use tracing::{
|
||||
Condvar, Mutex, MutexGuard, Once, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard,
|
||||
};
|
||||
|
||||
/// Dependency tracing versions of [`std::sync`].
|
||||
pub mod tracing {
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::sync;
|
||||
use std::sync::LockResult;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::Once;
|
||||
use std::sync::OnceState;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::RwLockReadGuard;
|
||||
use std::sync::RwLockWriteGuard;
|
||||
use std::sync::TryLockError;
|
||||
use std::sync::TryLockResult;
|
||||
use std::sync::WaitTimeoutResult;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::BorrowedMutex;
|
||||
use crate::LazyMutexId;
|
||||
use crate::MutexId;
|
||||
|
||||
/// Debug-only tracing `Mutex`.
|
||||
///
|
||||
/// Type alias that resolves to [`TracingMutex`] when debug assertions are enabled and to
|
||||
/// [`std::sync::Mutex`] when they're not. Use this if you want to have the benefits of cycle
|
||||
/// detection in development but do not want to pay the performance penalty in release.
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugMutex<T> = TracingMutex<T>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugMutex<T> = Mutex<T>;
|
||||
|
||||
/// Mutex guard for [`DebugMutex`].
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugMutexGuard<'a, T> = TracingMutexGuard<'a, T>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugMutexGuard<'a, T> = MutexGuard<'a, T>;
|
||||
|
||||
/// Debug-only tracing `RwLock`.
|
||||
///
|
||||
/// Type alias that resolves to [`TracingRwLock`] when debug assertions are enabled and to
|
||||
/// [`std::sync::RwLock`] when they're not. Use this if you want to have the benefits of cycle
|
||||
/// detection in development but do not want to pay the performance penalty in release.
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugRwLock<T> = TracingRwLock<T>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugRwLock<T> = RwLock<T>;
|
||||
|
||||
/// Read guard for [`DebugRwLock`].
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugReadGuard<'a, T> = TracingReadGuard<'a, T>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugReadGuard<'a, T> = RwLockReadGuard<'a, T>;
|
||||
|
||||
/// Write guard for [`DebugRwLock`].
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugWriteGuard<'a, T> = TracingWriteGuard<'a, T>;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugWriteGuard<'a, T> = RwLockWriteGuard<'a, T>;
|
||||
|
||||
/// Debug-only tracing `Once`.
|
||||
///
|
||||
/// Type alias that resolves to [`TracingOnce`] when debug assertions are enabled and to
|
||||
/// [`std::sync::Once`] when they're not. Use this if you want to have the benefits of cycle
|
||||
/// detection in development but do not want to pay the performance penalty in release.
|
||||
#[cfg(debug_assertions)]
|
||||
pub type DebugOnce = TracingOnce;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub type DebugOnce = Once;
|
||||
|
||||
/// Wrapper for [`std::sync::Mutex`].
|
||||
///
|
||||
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and
|
||||
/// Refer to the [crate-level][`crate`] documentation for the differences between this struct and
|
||||
/// the one it wraps.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TracingMutex<T> {
|
||||
inner: Mutex<T>,
|
||||
id: MutexId,
|
||||
pub struct Mutex<T> {
|
||||
inner: sync::Mutex<T>,
|
||||
id: LazyMutexId,
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::MutexGuard`].
|
||||
///
|
||||
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and
|
||||
/// Refer to the [crate-level][`crate`] documentation for the differences between this struct and
|
||||
/// the one it wraps.
|
||||
#[derive(Debug)]
|
||||
pub struct TracingMutexGuard<'a, T> {
|
||||
inner: MutexGuard<'a, T>,
|
||||
pub struct MutexGuard<'a, T> {
|
||||
inner: sync::MutexGuard<'a, T>,
|
||||
_mutex: BorrowedMutex<'a>,
|
||||
}
|
||||
|
||||
@@ -123,12 +90,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> TracingMutex<T> {
|
||||
impl<T> Mutex<T> {
|
||||
/// Create a new tracing mutex with the provided value.
|
||||
pub fn new(t: T) -> Self {
|
||||
pub const fn new(t: T) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(t),
|
||||
id: MutexId::new(),
|
||||
inner: sync::Mutex::new(t),
|
||||
id: LazyMutexId::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,11 +106,11 @@ impl<T> TracingMutex<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn lock(&self) -> LockResult<TracingMutexGuard<T>> {
|
||||
pub fn lock(&self) -> LockResult<MutexGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.lock();
|
||||
|
||||
let mapper = |guard| TracingMutexGuard {
|
||||
let mapper = |guard| MutexGuard {
|
||||
_mutex: mutex,
|
||||
inner: guard,
|
||||
};
|
||||
@@ -158,11 +125,11 @@ impl<T> TracingMutex<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn try_lock(&self) -> TryLockResult<TracingMutexGuard<T>> {
|
||||
pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.try_lock();
|
||||
|
||||
let mapper = |guard| TracingMutexGuard {
|
||||
let mapper = |guard| MutexGuard {
|
||||
_mutex: mutex,
|
||||
inner: guard,
|
||||
};
|
||||
@@ -188,13 +155,13 @@ impl<T> TracingMutex<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for TracingMutex<T> {
|
||||
impl<T> From<T> for Mutex<T> {
|
||||
fn from(t: T) -> Self {
|
||||
Self::new(t)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Deref for TracingMutexGuard<'a, T> {
|
||||
impl<'a, T> Deref for MutexGuard<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
@@ -202,28 +169,140 @@ impl<'a, T> Deref for TracingMutexGuard<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> DerefMut for TracingMutexGuard<'a, T> {
|
||||
impl<'a, T> DerefMut for MutexGuard<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: fmt::Display> fmt::Display for TracingMutexGuard<'a, T> {
|
||||
impl<'a, T: fmt::Display> fmt::Display for MutexGuard<'a, T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.inner.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper around [`std::sync::Condvar`].
|
||||
///
|
||||
/// Allows `TracingMutexGuard` to be used with a `Condvar`. Unlike other structs in this module,
|
||||
/// this wrapper does not add any additional dependency tracking or other overhead on top of the
|
||||
/// primitive it wraps. All dependency tracking happens through the mutexes itself.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This struct does not add any panics over the base implementation of `Condvar`, but panics due to
|
||||
/// dependency tracking may poison associated mutexes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use std::sync::Arc;
|
||||
/// use std::thread;
|
||||
///
|
||||
/// use tracing_mutex::stdsync::tracing::{Condvar, Mutex};
|
||||
///
|
||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
/// let pair2 = Arc::clone(&pair);
|
||||
///
|
||||
/// // Spawn a thread that will unlock the condvar
|
||||
/// thread::spawn(move || {
|
||||
/// let (lock, condvar) = &*pair2;
|
||||
/// *lock.lock().unwrap() = true;
|
||||
/// condvar.notify_one();
|
||||
/// });
|
||||
///
|
||||
/// // Wait until the thread unlocks the condvar
|
||||
/// let (lock, condvar) = &*pair;
|
||||
/// let guard = lock.lock().unwrap();
|
||||
/// let guard = condvar.wait_while(guard, |started| !*started).unwrap();
|
||||
///
|
||||
/// // Guard should read true now
|
||||
/// assert!(*guard);
|
||||
/// ```
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Condvar(sync::Condvar);
|
||||
|
||||
impl Condvar {
|
||||
/// Creates a new condition variable which is ready to be waited on and notified.
|
||||
pub const fn new() -> Self {
|
||||
Self(sync::Condvar::new())
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::wait`].
|
||||
pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
|
||||
let MutexGuard { _mutex, inner } = guard;
|
||||
|
||||
map_lockresult(self.0.wait(inner), |inner| MutexGuard { _mutex, inner })
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::wait_while`].
|
||||
pub fn wait_while<'a, T, F>(
|
||||
&self,
|
||||
guard: MutexGuard<'a, T>,
|
||||
condition: F,
|
||||
) -> LockResult<MutexGuard<'a, T>>
|
||||
where
|
||||
F: FnMut(&mut T) -> bool,
|
||||
{
|
||||
let MutexGuard { _mutex, inner } = guard;
|
||||
|
||||
map_lockresult(self.0.wait_while(inner, condition), |inner| MutexGuard {
|
||||
_mutex,
|
||||
inner,
|
||||
})
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::wait_timeout`].
|
||||
pub fn wait_timeout<'a, T>(
|
||||
&self,
|
||||
guard: MutexGuard<'a, T>,
|
||||
dur: Duration,
|
||||
) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
|
||||
let MutexGuard { _mutex, inner } = guard;
|
||||
|
||||
map_lockresult(self.0.wait_timeout(inner, dur), |(inner, result)| {
|
||||
(MutexGuard { _mutex, inner }, result)
|
||||
})
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::wait_timeout_while`].
|
||||
pub fn wait_timeout_while<'a, T, F>(
|
||||
&self,
|
||||
guard: MutexGuard<'a, T>,
|
||||
dur: Duration,
|
||||
condition: F,
|
||||
) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
|
||||
where
|
||||
F: FnMut(&mut T) -> bool,
|
||||
{
|
||||
let MutexGuard { _mutex, inner } = guard;
|
||||
|
||||
map_lockresult(
|
||||
self.0.wait_timeout_while(inner, dur, condition),
|
||||
|(inner, result)| (MutexGuard { _mutex, inner }, result),
|
||||
)
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::notify_one`].
|
||||
pub fn notify_one(&self) {
|
||||
self.0.notify_one();
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::Condvar::notify_all`].
|
||||
pub fn notify_all(&self) {
|
||||
self.0.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::RwLock`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TracingRwLock<T> {
|
||||
inner: RwLock<T>,
|
||||
id: MutexId,
|
||||
pub struct RwLock<T> {
|
||||
inner: sync::RwLock<T>,
|
||||
id: LazyMutexId,
|
||||
}
|
||||
|
||||
/// Hybrid wrapper for both [`std::sync::RwLockReadGuard`] and [`std::sync::RwLockWriteGuard`].
|
||||
///
|
||||
/// Please refer to [`TracingReadGuard`] and [`TracingWriteGuard`] for usable types.
|
||||
/// Please refer to [`RwLockReadGuard`] and [`RwLockWriteGuard`] for usable types.
|
||||
#[derive(Debug)]
|
||||
pub struct TracingRwLockGuard<'a, L> {
|
||||
inner: L,
|
||||
@@ -231,15 +310,15 @@ pub struct TracingRwLockGuard<'a, L> {
|
||||
}
|
||||
|
||||
/// Wrapper around [`std::sync::RwLockReadGuard`].
|
||||
pub type TracingReadGuard<'a, T> = TracingRwLockGuard<'a, RwLockReadGuard<'a, T>>;
|
||||
pub type RwLockReadGuard<'a, T> = TracingRwLockGuard<'a, sync::RwLockReadGuard<'a, T>>;
|
||||
/// Wrapper around [`std::sync::RwLockWriteGuard`].
|
||||
pub type TracingWriteGuard<'a, T> = TracingRwLockGuard<'a, RwLockWriteGuard<'a, T>>;
|
||||
pub type RwLockWriteGuard<'a, T> = TracingRwLockGuard<'a, sync::RwLockWriteGuard<'a, T>>;
|
||||
|
||||
impl<T> TracingRwLock<T> {
|
||||
pub fn new(t: T) -> Self {
|
||||
impl<T> RwLock<T> {
|
||||
pub const fn new(t: T) -> Self {
|
||||
Self {
|
||||
inner: RwLock::new(t),
|
||||
id: MutexId::new(),
|
||||
inner: sync::RwLock::new(t),
|
||||
id: LazyMutexId::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +329,7 @@ impl<T> TracingRwLock<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn read(&self) -> LockResult<TracingReadGuard<T>> {
|
||||
pub fn read(&self) -> LockResult<RwLockReadGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.read();
|
||||
|
||||
@@ -267,7 +346,7 @@ impl<T> TracingRwLock<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn write(&self) -> LockResult<TracingWriteGuard<T>> {
|
||||
pub fn write(&self) -> LockResult<RwLockWriteGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.write();
|
||||
|
||||
@@ -284,7 +363,7 @@ impl<T> TracingRwLock<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn try_read(&self) -> TryLockResult<TracingReadGuard<T>> {
|
||||
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.try_read();
|
||||
|
||||
@@ -301,7 +380,7 @@ impl<T> TracingRwLock<T> {
|
||||
/// This method participates in lock dependency tracking. If acquiring this lock introduces a
|
||||
/// dependency cycle, this method will panic.
|
||||
#[track_caller]
|
||||
pub fn try_write(&self) -> TryLockResult<TracingWriteGuard<T>> {
|
||||
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
|
||||
let mutex = self.id.get_borrowed();
|
||||
let result = self.inner.try_write();
|
||||
|
||||
@@ -324,7 +403,7 @@ impl<T> TracingRwLock<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for TracingRwLock<T> {
|
||||
impl<T> From<T> for RwLock<T> {
|
||||
fn from(t: T) -> Self {
|
||||
Self::new(t)
|
||||
}
|
||||
@@ -352,19 +431,19 @@ where
|
||||
|
||||
/// Wrapper around [`std::sync::Once`].
|
||||
///
|
||||
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and
|
||||
/// the one it wraps.
|
||||
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct
|
||||
/// and the one it wraps.
|
||||
#[derive(Debug)]
|
||||
pub struct TracingOnce {
|
||||
inner: Once,
|
||||
pub struct Once {
|
||||
inner: sync::Once,
|
||||
mutex_id: LazyMutexId,
|
||||
}
|
||||
|
||||
impl TracingOnce {
|
||||
impl Once {
|
||||
/// Create a new `Once` value.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: Once::new(),
|
||||
inner: sync::Once::new(),
|
||||
mutex_id: LazyMutexId::new(),
|
||||
}
|
||||
}
|
||||
@@ -383,7 +462,7 @@ impl TracingOnce {
|
||||
self.inner.call_once(f);
|
||||
}
|
||||
|
||||
/// Performs the same operation as [`call_once`][TracingOnce::call_once] except it ignores
|
||||
/// Performs the same operation as [`call_once`][Once::call_once] except it ignores
|
||||
/// poisoning.
|
||||
///
|
||||
/// # Panics
|
||||
@@ -404,6 +483,142 @@ impl TracingOnce {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper for [`std::sync::OnceLock`]
|
||||
///
|
||||
/// The exact locking behaviour of [`std::sync::OnceLock`] is currently undefined, but may
|
||||
/// deadlock in the event of reentrant initialization attempts. This wrapper participates in
|
||||
/// cycle detection as normal and will therefore panic in the event of reentrancy.
|
||||
///
|
||||
/// Most of this primitive's methods do not involve locking and as such are simply passed
|
||||
/// through to the inner implementation.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tracing_mutex::stdsync::tracing::OnceLock;
|
||||
///
|
||||
/// static LOCK: OnceLock<i32> = OnceLock::new();
|
||||
/// assert!(LOCK.get().is_none());
|
||||
///
|
||||
/// std::thread::spawn(|| {
|
||||
/// let value: &i32 = LOCK.get_or_init(|| 42);
|
||||
/// assert_eq!(value, &42);
|
||||
/// }).join().unwrap();
|
||||
///
|
||||
/// let value: Option<&i32> = LOCK.get();
|
||||
/// assert_eq!(value, Some(&42));
|
||||
/// ```
|
||||
#[derive(Debug)]
|
||||
pub struct OnceLock<T> {
|
||||
id: LazyMutexId,
|
||||
inner: sync::OnceLock<T>,
|
||||
}
|
||||
|
||||
// N.B. this impl inlines everything that directly calls the inner implementation as there
|
||||
// should be 0 overhead to doing so.
|
||||
impl<T> OnceLock<T> {
|
||||
/// Creates a new empty cell
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
id: LazyMutexId::new(),
|
||||
inner: sync::OnceLock::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a reference to the underlying value.
|
||||
///
|
||||
/// This method does not attempt to lock and therefore does not participate in cycle
|
||||
/// detection.
|
||||
#[inline]
|
||||
pub fn get(&self) -> Option<&T> {
|
||||
self.inner.get()
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the underlying value.
|
||||
///
|
||||
/// This method does not attempt to lock and therefore does not participate in cycle
|
||||
/// detection.
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self) -> Option<&mut T> {
|
||||
self.inner.get_mut()
|
||||
}
|
||||
|
||||
/// Sets the contents of this cell to the underlying value
|
||||
///
|
||||
/// As this method may block until initialization is complete, it participates in cycle
|
||||
/// detection.
|
||||
pub fn set(&self, value: T) -> Result<(), T> {
|
||||
let _guard = self.id.get_borrowed();
|
||||
|
||||
self.inner.set(value)
|
||||
}
|
||||
|
||||
/// Gets the contents of the cell, initializing it with `f` if the cell was empty.
|
||||
///
|
||||
/// This method participates in cycle detection. Reentrancy is considered a cycle.
|
||||
pub fn get_or_init<F>(&self, f: F) -> &T
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
{
|
||||
let _guard = self.id.get_borrowed();
|
||||
self.inner.get_or_init(f)
|
||||
}
|
||||
|
||||
/// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
|
||||
///
|
||||
/// This method does not attempt to lock and therefore does not participate in cycle
|
||||
/// detection.
|
||||
#[inline]
|
||||
pub fn take(&mut self) -> Option<T> {
|
||||
self.inner.take()
|
||||
}
|
||||
|
||||
/// Consumes the `OnceLock`, returning the wrapped value. Returns None if the cell was
|
||||
/// empty.
|
||||
///
|
||||
/// This method does not attempt to lock and therefore does not participate in cycle
|
||||
/// detection.
|
||||
#[inline]
|
||||
pub fn into_inner(mut self) -> Option<T> {
|
||||
self.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for OnceLock<T> {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for OnceLock<T> {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inner == other.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Eq> Eq for OnceLock<T> {}
|
||||
|
||||
impl<T: Clone> Clone for OnceLock<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
id: LazyMutexId::new(),
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for OnceLock<T> {
|
||||
#[inline]
|
||||
fn from(value: T) -> Self {
|
||||
Self {
|
||||
id: LazyMutexId::new(),
|
||||
inner: sync::OnceLock::from(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
@@ -413,7 +628,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_mutex_usage() {
|
||||
let mutex = Arc::new(TracingMutex::new(0));
|
||||
let mutex = Arc::new(Mutex::new(0));
|
||||
|
||||
assert_eq!(*mutex.lock().unwrap(), 0);
|
||||
*mutex.lock().unwrap() = 1;
|
||||
@@ -435,7 +650,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rwlock_usage() {
|
||||
let rwlock = Arc::new(TracingRwLock::new(0));
|
||||
let rwlock = Arc::new(RwLock::new(0));
|
||||
|
||||
assert_eq!(*rwlock.read().unwrap(), 0);
|
||||
assert_eq!(*rwlock.write().unwrap(), 0);
|
||||
@@ -462,7 +677,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_once_usage() {
|
||||
let once = Arc::new(TracingOnce::new());
|
||||
let once = Arc::new(Once::new());
|
||||
let once_clone = once.clone();
|
||||
|
||||
assert!(!once.is_completed());
|
||||
@@ -481,10 +696,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Mutex order graph should not have cycles")]
|
||||
#[should_panic(expected = "Found cycle in mutex dependency graph")]
|
||||
fn test_detect_cycle() {
|
||||
let a = TracingMutex::new(());
|
||||
let b = TracingMutex::new(());
|
||||
let a = Mutex::new(());
|
||||
let b = Mutex::new(());
|
||||
|
||||
let hold_a = a.lock().unwrap();
|
||||
let _ = b.lock();
|
||||
@@ -495,3 +710,4 @@ mod tests {
|
||||
let _ = a.lock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user