Concurrency Coordination Reports
Mutex Try-Lock Coordination Report
A coordination report records nonblocking lock attempts. This program uses Mutex::try_lock, keeps each acquired guard, and reports whether a later attempt was blocked.
Program
Play the program to choose how many acquire attempts run and watch the guard report stay open or block.
mutex_try_lock_coordination_report.rs
use std::sync::Mutex;
fn main() {
let holds = ;
let lock = Mutex::new(0u32);
let mut acquired = 0;
let mut blocked = 0;
let mut kept = Vec::new();
for _ in 0..holds {
match lock.try_lock() {
Ok(guard) => {
acquired += 1;
kept.push(guard);
}
Err(_) => blocked += 1,
}
}
let status = if acquired == 0 {
"idle"
} else if blocked > 0 {
"blocked"
} else {
"guarded"
};
println!("holds={holds} acquired={acquired} blocked={blocked} {status}");
}
use std::sync::Mutex;
fn main() {
let holds = ;
let lock = Mutex::new(0u32);
let mut acquired = 0;
let mut blocked = 0;
let mut kept = Vec::new();
for _ in 0..holds {
match lock.try_lock() {
Ok(guard) => {
acquired += 1;
kept.push(guard);
}
Err(_) => blocked += 1,
}
}
let status = if acquired == 0 {
"idle"
} else if blocked > 0 {
"blocked"
} else {
"guarded"
};
println!("holds={holds} acquired={acquired} blocked={blocked} {status}");
}
use std::sync::Mutex;
fn main() {
let holds = ;
let lock = Mutex::new(0u32);
let mut acquired = 0;
let mut blocked = 0;
let mut kept = Vec::new();
for _ in 0..holds {
match lock.try_lock() {
Ok(guard) => {
acquired += 1;
kept.push(guard);
}
Err(_) => blocked += 1,
}
}
let status = if acquired == 0 {
"idle"
} else if blocked > 0 {
"blocked"
} else {
"guarded"
};
println!("holds={holds} acquired={acquired} blocked={blocked} {status}");
}
nonblocking acquire
`Mutex::try_lock` returns `Ok` when it takes the guard and `Err` when the guard is already held, so it never blocks.
held guard
Pushing each acquired guard into `kept` keeps the lock held, so a later attempt in the same run is reported as blocked.
coordination status
The status line summarizes whether the section stayed idle, guarded, or blocked a later acquire.