Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AurevoirXavier/fee1a1a1662b60f340fa312938c38abc to your computer and use it in GitHub Desktop.
Save AurevoirXavier/fee1a1a1662b60f340fa312938c38abc to your computer and use it in GitHub Desktop.
[Rust] Write to shared memory from multiple threads

I'm having some trouble trying to figure out how to share mutable data between threads.

I have a Vec I want multiple threads to write to simultaneously. I don't care if the threads tries to write to the same index (data races are allowed in this context).

How do I go about doing this?

@AurevoirXavier
Copy link
Author


pcpthm:

No, it is never allowed. Rust explicitly says that any data race 2 is an instant UB (undefined behavior). You have to use an atomic operation even if the result doesn't matter.

I don't know what you want to achieve but here is an example of sharing a Vec between threads and threads "race" (but not a data race) for a write:

use std::sync::{Arc, atomic::{AtomicI32, Ordering}};
use std::thread;
fn main() {
    let v = Arc::new(vec![AtomicI32::new(1), AtomicI32::new(2)]);
    {
        let v = Arc::clone(&v);
        thread::spawn(move || v[0].store(2, Ordering::Relaxed));
    };
    {
        let v = Arc::clone(&v);
        thread::spawn(move || v[0].store(3, Ordering::Relaxed));
    };
    // The output is nondeterministic.
    for _ in 0..5 {
        println!("{}", v[0].load(Ordering::Relaxed));
    }
}

mbrubeck:

Atomic operations also inhibit compiler optimizations that would result in incorrect code in the presence of data races. This means that they can have performance impact and are necessary for soundness and correctness even if you compile only on platforms where the atomic reads/writes use the same instructions as non-atomic ones.


More detail: https://users.rust-lang.org/t/write-to-shared-memory-from-multiple-threads/34587

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment