rust
43 lines · 7 steps
A self-timing mutex guard in Rust
Wrapping a MutexGuard in a custom type lets you log how long a lock is held using RAII.
Explained by
highlit
1use std::sync::{Arc, Mutex, MutexGuard};
2use std::time::Instant;
3
4pub struct TimedGuard<'a, T> {
5 inner: MutexGuard<'a, T>,
6 label: &'static str,
7 acquired: Instant,
8}
9
10impl<'a, T> TimedGuard<'a, T> {
11 pub fn acquire(mutex: &'a Mutex<T>, label: &'static str) -> Self {
12 let acquired = Instant::now();
13 let inner = mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
14 log::debug!("acquired lock '{}'", label);
15 Self { inner, label, acquired }
16 }
17}
18
19impl<'a, T> std::ops::Deref for TimedGuard<'a, T> {
20 type Target = T;
21 fn deref(&self) -> &T {
22 &self.inner
23 }
24}
25
26impl<'a, T> std::ops::DerefMut for TimedGuard<'a, T> {
27 fn deref_mut(&mut self) -> &mut T {
28 &mut self.inner
29 }
30}
31
32impl<'a, T> Drop for TimedGuard<'a, T> {
33 fn drop(&mut self) {
34 let held = self.acquired.elapsed();
35 log::debug!("released lock '{}' after {:.2}ms", self.label, held.as_secs_f64() * 1000.0);
36 }
37}
38
39pub fn credit_balance(account: &Arc<Mutex<u64>>, amount: u64) -> u64 {
40 let mut balance = TimedGuard::acquire(account, "account_balance");
41 *balance = balance.saturating_add(amount);
42 *balance
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping a guard in your own type lets you attach behavior to a lock's entire lifetime.
- 2Implementing Deref and DerefMut makes a wrapper transparent so callers use it like the value itself.
- 3Drop turns scope exit into a reliable hook for cleanup or measurement without explicit calls.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-self-timing-mutex-guard-in-rust-explained-rust-d65b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.