Skip to content

Instantly share code, notes, and snippets.

@abradley2
Created November 15, 2024 04:08
Show Gist options
  • Save abradley2/3ca8955108ed698cf431e7854823e311 to your computer and use it in GitHub Desktop.
Save abradley2/3ca8955108ed698cf431e7854823e311 to your computer and use it in GitHub Desktop.
Regular Rust Async Example
use std::{sync::{mpsc::channel, Arc, Mutex}, thread, time::Duration};
fn main() {
let result = run();
assert_eq!(result, 3)
}
struct Counter {
value: u32,
}
fn run() -> u32 {
let counter = Arc::new(Mutex::new(Counter { value: 0 }));
let (snd, rcv) = channel::<()>();
let snd_arc = Arc::new(snd);
let counter_1 = Arc::clone(&counter);
let done_1 = Arc::clone(&snd_arc);
thread::spawn(move || {
thread::sleep(Duration::new(1, 0));
counter_1.lock().unwrap().value += 1;
done_1.send(())
});
let counter_2 = Arc::clone(&counter);
let done_2 = Arc::clone(&snd_arc);
thread::spawn(move || {
thread::sleep(Duration::new(3, 0));
counter_2.lock().unwrap().value += 1;
done_2.send(())
});
let counter_3 = Arc::clone(&counter);
let done_3 = Arc::clone(&snd_arc);
thread::spawn(move || {
thread::sleep(Duration::new(2, 0));
counter_3.lock().unwrap().value += 1;
done_3.send(())
});
while Arc::strong_count(&snd_arc) > 1 {
let _ = rcv.recv();
};
let final_value = counter.lock().unwrap().value;
final_value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment