Skip to main content

suspend/
suspend.rs

1use std::sync::{
2    atomic::{spin_loop_hint, AtomicUsize, Ordering},
3    Arc,
4};
5use std::thread;
6use suspend::{block_on, Suspend};
7
8fn main() {
9    let exchange1 = Arc::new(AtomicUsize::new(0));
10    let exchange2 = exchange1.clone();
11    let mut susp = Suspend::new();
12    let notifier = susp.notifier();
13
14    let handle = thread::spawn(move || {
15        let listen = susp.listen();
16        let exchange1_1 = exchange1.clone();
17        block_on(async move {
18            exchange1_1.store(1, Ordering::Release);
19            // wait in an async context
20            listen.await
21        });
22
23        let mut listen = susp.listen();
24        exchange1.store(2, Ordering::Release);
25        // block on a notification
26        listen.wait()
27    });
28
29    thread::spawn(move || {
30        for i in 1..=2 {
31            while exchange2.load(Ordering::Acquire) != i {
32                spin_loop_hint();
33            }
34            notifier.notify();
35        }
36    });
37
38    handle.join().unwrap();
39}