Is this a possible result when using atomic in asynchronous programming

⚓ rust    📅 2025-05-28    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.
use std::sync::atomic::{AtomicI32,Ordering};
static ATOM:AtomicI32 = AtomicI32::new(0);
async fn fun1(){
    blocking::unblock(||{
        std::thread::sleep(std::time::Duration::from_millis(108));
        ATOM.store(1, Ordering::Relaxed);
        println!("ok");
    }).await;
}

#[tokio::main]
async fn main() {
    for _i in 0..60{
        tokio::select! {
            _=tokio::time::sleep(std::time::Duration::from_millis(100))=>{  // #1
                let r = ATOM.load(Ordering::Relaxed);
                println!("sleep, detect:{r}");
            }
            _=fun1()=>{
                println!("fun1");
            }
        }
        println!("----------------------");
    }
}

Consider the following example: Is this result possible?

ok
sleep, detect:0

That is, in the thread pool, the println!("ok") is executed, however, the branch at #1 wins the race, and sleep is printed, but the result of the load is 0? Is this a theoretically possible result

5 posts - 3 participants

Read full topic

🏷️ rust_feed