typestar

Atomics in Rust

For a counter or a flag, an atomic is cheaper than a mutex.

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;

fn main() {
    let hits = Arc::new(AtomicUsize::new(0));
    let done = Arc::new(AtomicBool::new(false));

    let handles: Vec<_> = (0..4)
        .map(|_| {
            let hits = Arc::clone(&hits);
            thread::spawn(move || {
                for _ in 0..500 {
                    hits.fetch_add(1, Ordering::Relaxed);
                }
            })
        })
        .collect();

    for h in handles {
        h.join().unwrap();
    }
    done.store(true, Ordering::Release);

    println!("{}", hits.load(Ordering::Acquire));
    println!("{}", done.load(Ordering::Acquire));
}

How it works

  1. fetch_add increments and returns the previous value.
  2. Ordering states how strict the memory guarantees must be.
  3. No lock, no guard, no chance of poisoning.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
540
Tokens
190
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 3 of 3 in Shared state, step 6 of 15 in Concurrency & async.

← Previous Next →