Re:What killed Haskell, could kill Rust, too
by acqq on Tuesday September 08, 2020 @04:01PM
(#24412465)
Thanks!
> You still need the mutexes because multiple threads are writing to the same variables at the same time
I understand that for the "data" for which the push exists. Do we however need it for res_mutex when the value that we want to update is a single (I guess integer) variable for which atomic add could be performed? Is there something like atomic add?
Re:What killed Haskell, could kill Rust, too
by steveklabnik on Tuesday September 08, 2020 @04:24PM
(#24412851)
Oh, duh, yes. one line added, two lines changed, I've left them at their indent levels and left the variable name the same:
use std::sync::atomic::{AtomicU32, Ordering};
let res_mutex = AtomicU32::new(0);
res_mutex.fetch_add(result, Ordering::SeqCst);
(You still need the mutexes because multiple threads are writing to the same variables at the same time; imagine if we didn't push the result onto the vector; we could drop the mutex around it entirely, which would simplify things even further. See the example here, where because we are accessing disjoint parts of the vector, we can use no mutexes at all: https://crates.io/crates/scoped_threadpool