|
|
|
@ -25,7 +25,7 @@ race condition can't violate memory safety in a Rust program on
|
|
|
|
|
its own. Only in conjunction with some other unsafe code can a race condition
|
|
|
|
|
actually violate memory safety. For instance:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
```rust,norun
|
|
|
|
|
use std::thread;
|
|
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
@ -54,6 +54,24 @@ thread::spawn(move || {
|
|
|
|
|
// program execution (panicing is rarely correct) depends on order of
|
|
|
|
|
// thread execution.
|
|
|
|
|
println!("{}", data[idx.load(Ordering::SeqCst)]);
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```rust,norun
|
|
|
|
|
use std::thread;
|
|
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
|
|
let data = vec![1, 2, 3, 4];
|
|
|
|
|
|
|
|
|
|
let idx = Arc::new(AtomicUsize::new(0));
|
|
|
|
|
let other_idx = idx.clone();
|
|
|
|
|
|
|
|
|
|
// `move` captures other_idx by-value, moving it into this thread
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
|
// It's ok to mutate idx because this value
|
|
|
|
|
// is an atomic, so it can't cause a Data Race.
|
|
|
|
|
other_idx.fetch_add(10, Ordering::SeqCst);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if idx.load(Ordering::SeqCst) < data.len() {
|
|
|
|
|
unsafe {
|
|
|
|
|