From 7ae0bd39890d6c35c92f7aa2ab4da0ef5b0f1c45 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sat, 18 Jan 2025 19:58:22 +0100 Subject: [PATCH] Add example showcasing how to replace parking_lot --- CHANGELOG.md | 4 ++++ Cargo.toml | 4 ++++ examples/drop_in_parking_lot.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 examples/drop_in_parking_lot.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 691bb38..4b9472c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - On Rust 1.80 or newer, a wrapper for `std::sync::LazyLock` is now available. The MSRV has not been changed; older versions simply don't get this wrapper. +- Added missing const-initialisation wrappers for `parking_lot`. The API interface for + `tracing_mutex::parkinglot` is now identical to `parking_lot`, and an example showing how to use + it as a drop-in replacement was added. + ### Changed - Reworked CI to better test continued support for the minimum supported Rust version diff --git a/Cargo.toml b/Cargo.toml index 4b28bc5..fc8bf29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,10 @@ rand = "0.8" name = "mutex" harness = false +[[example]] +name = "drop_in_parking_lot" +required-features = ["parkinglot"] + [features] default = ["backtraces"] backtraces = [] diff --git a/examples/drop_in_parking_lot.rs b/examples/drop_in_parking_lot.rs new file mode 100644 index 0000000..916e83d --- /dev/null +++ b/examples/drop_in_parking_lot.rs @@ -0,0 +1,32 @@ +//! This example shows how you can use the [`tracing-mutex`] crate as a drop-in replacement for the +//! parking_lot crate. By default, `tracing-mutex` offers a set of type aliases that allows you to +//! use cycle-checking in development, and raw primitives in release mode, but this way, you can +//! even remove the dependency altogether, or hide it behind a feature. +//! +//! You can use whatever conditional compilation makes sense in context. +use std::sync::Arc; + +#[cfg(not(debug_assertions))] +use parking_lot; + +#[cfg(debug_assertions)] +// Note: specifically use the `tracing` module, because at this point we are very sure we want to do +// deadlock tracing, so no need to use the automatic selection. +use tracing_mutex::parkinglot::tracing as parking_lot; + +fn main() { + let mutex = Arc::new(parking_lot::const_mutex(0)); + + let handles: Vec<_> = (0..42) + .map(|_| { + let mutex = Arc::clone(&mutex); + std::thread::spawn(move || *mutex.lock() += 1) + }) + .collect(); + + handles + .into_iter() + .for_each(|handle| handle.join().unwrap()); + + assert_eq!(*mutex.lock(), 42); +}