Search code examples
rustconcurrencymutexinstruction-reordering

Compiler reordering section with mutual exclusion


Since rust applies the mutex as a container/owner of its data and doesn't use an external guard like C++, I was wondering whether the rust compiler might reorder the internal part of the loop in the following pseudo-code (and by doing so, invalidate it..) and if so, how can I prevent it?

let mut some_type = SomeType::new();
let mut my_lock = MyLock::new();
(0..n).par_iter().for_each(|| {
     my_lock.lock();
     do_some_stuff_with(&mut some_type);
     my_lock.unlock();
}) 

Solution

  • Rust actually uses the same memory model as C++20. So AFAIK you can protect code with a lock, it's just not a great idea (because nothing actually precludes unsynchronised access to the shared resource, and there usually is one you want to protect anyway), and also a bit error prone as you need to ensure you're keeping the mutexguard alive.

    I really don't see the point here:

    let mut my_lock = Mutex::new(SomeType::new());
    (0..n).par_iter().for_each(|| {
         let mut some_type = my_lock.lock().unwrap();
         do_some_stuff_with(&mut some_type);
    })
    

    and of course the par_iter is completely useless since: you're locking the entire callback, so you're just doing a linear iteration, except non-sequential and with a ton of overhead.