Atomics and save Ordering

I try to get familiar with Rust's Atomics. As I am still hesitating to downgrade the
Ordering, I would like to get advice from someone more experienced:

  1. Portability

    Is there a common set of Atomic types and methods available on all platforms that can run std? Which ones?

    Some hints about portability I found so far.

  2. How can Ordering::SeqCst safely be downgraded in the following scenario?

    Edit: store() and load() happen in different threads.

    pub struct AppLogger {
        popup_always_enabled: AtomicBool,
    }
    
    lazy_static! {
        static ref APP_LOGGER: AppLogger = AppLogger {
    	popup_always_enabled: AtomicBool::new(calculated_flag)
        };
    }
    
    ...
    
    APP_LOGGER.popup_always_enabled.store(true, Ordering::SeqCst);
    
    ...
    
    let flag = APP_LOGGER.popup_always_enabled.load(Ordering::SeqCst));
    
  3. How can Ordering::SeqCst safely downgraded in the following scenario?

    Edit: store() and load() happen in different threads.

    let terminate_on_browser_disconnect = Arc::new(AtomicBool::new(false));
    let terminate_on_browser_disconnect_ = terminate_on_browser_disconnect.clone();
    thread::spawn(move || {
           let flag = terminate_on_browser_disconnect.load_(Ordering::SeqCst);
           ...
    }
    ...
    terminate_on_browser_disconnect.store(calculated_flag, Ordering::SeqCst);
    
    

Edit: It seems to me that load() should be load(Ordering::Acquire)
and store() should be store(..., Ordering::Release). Is this right?

Regarding portability, the AtomicU64 type is less available than the others.

I don't think ordering matters much for your use-case.

The lazy_static is not necessary. You can use a real static.

1 Like

@alice Form your answer I noticed, that my question was not precise enough. I added Edit: .... to mark the changes.

I still don't think it matters much here. If you want a more in-depth information on atomics, check out the talk "atomic Weapons" by Herb Sutter.

2 Likes

If you want a more in-depth information on atomics, check out the talk "atomic Weapons" by Herb Sutter.

Thank you Alice, I will check this out. (For completeness: Crust of Rust: Atomics and Memory Ordering - YouTube)

I still don't think it matters much here.

Do you think, I could even set it to Ordering::relaxed?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.