4 ms·
This is not a data race in the sense that Rust prevents. Case in point, here is the same race condition in Rust: - playground[0] (see for yourself) - inline
by dureuill 5y ago
This is not a data race in the sense that Rust prevents.
Case in point, here is the same race condition in Rust:
- playground[0] (see for yourself)
- inline code (not that long):
use std::thread;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
static COUNTER : AtomicU32 = AtomicU32::new(0);
fn increase() {
for _i in 0..100000 {
let a = COUNTER.load(Ordering::SeqCst);
COUNTER.store(a + 1, Ordering::SeqCst);
}
}
fn main() {
let mut threads = Vec::new();
for _i in 0..400 {
threads.push(thread::spawn(increase))
}
for thread in threads {
thread.join().unwrap();
}
println!("Final counter: {}", COUNTER.load(Ordering::SeqCst))
}
The data races that Rust prevents are "instruction-level data races". They occur when a single, non atomic, architectural instruction is executed in parallel by multiple threads. In that case we can really get corrupted values, in that "partially written" value in the architectural sense (depending on architectural details) can be produced. Think a double word with one word rewritten by one thread and the other word rewritten by the other thread.
In the given code example that is not an instruction-level data race, the produced value will strictly be in the range <max_number_of_increase>..<max_number_of_increase>*<number_of_threads> (plus or minus the usual off-by-one error), and no architectural artifacts can ever manifest.
I guess the insight of the article could be that `counter = counter + 1` is closer in Python from `a = atomicLoad(counter); atomicStore(counter, a + 1)` than from `atomicIncrement(counter)`?
I wonder if using `counter += 1` changes anything? In any case, I can see how it is easier to trigger accidental race conditions of that kind in Python than in Rust, with the atomic operations being implicit in the former, and explicit in the latter.
[0]: https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=13c380a005dd43056eba8f63c9563403 https://play.rust-lang.org/?version=stable&mode=release&edit...