expression

Logical race versus data race

Safe synchronization prevents unsynchronized conflicting memory access, but a check made under one acquisition may be stale by the next. Keep a check-and-update operation indivisible with respect to other users of that mutex. Expected stdout (not executed): 1 0 Common mistake: Checking stock under one lock and decrementing under another without rechecking.

Formal Syntax & Structure

rust syntaxrust
check and update under the same guard

Working Example

Example Snippetrust
fn main() {    use std::sync::Mutex;    let stock = Mutex::new(1u32);    let sold = std::thread::scope(|s| {        let buy = || { let mut g = stock.lock().unwrap(); if *g > 0 { *g -= 1; 1 } else { 0 } };        let a = s.spawn(buy); let b = s.spawn(buy);        a.join().unwrap() + b.join().unwrap()    });    println!("{} {}", sold, stock.into_inner().unwrap());}
Rust Reference