File: simple.rs

package info (click to toggle)
rust-atom 0.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 212 kB
  • sloc: makefile: 4
file content (33 lines) | stat: -rw-r--r-- 909 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
extern crate atom;

use atom::*;
use std::sync::{atomic::Ordering, Arc};
use std::thread;

fn main() {
    // Create an empty atom
    let shared_atom = Arc::new(Atom::empty());

    // set the value 75
    shared_atom.swap(Box::new(75), Ordering::AcqRel);

    // Spawn a bunch of thread that will try and take the value
    let threads: Vec<thread::JoinHandle<()>> = (0..8)
        .map(|_| {
            let shared_atom = shared_atom.clone();
            thread::spawn(move || {
                // Take the contents of the atom, only one will win the race
                if let Some(v) = shared_atom.take(Ordering::Acquire) {
                    println!("I got it: {:?} :D", v);
                } else {
                    println!("I did not get it :(");
                }
            })
        })
        .collect();

    // join the threads
    for t in threads {
        t.join().unwrap();
    }
}