File tree Expand file tree Collapse file tree 1 file changed +19
-1
lines changed Expand file tree Collapse file tree 1 file changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -25,7 +25,7 @@ race condition can't violate memory safety in a Rust program on
2525its own. Only in conjunction with some other unsafe code can a race condition
2626actually violate memory safety. For instance:
2727
28- ``` rust
28+ ``` rust,norun
2929use std::thread;
3030use std::sync::atomic::{AtomicUsize, Ordering};
3131use std::sync::Arc;
@@ -54,6 +54,24 @@ thread::spawn(move || {
5454// program execution (panicing is rarely correct) depends on order of
5555// thread execution.
5656println!("{}", data[idx.load(Ordering::SeqCst)]);
57+ ```
58+
59+ ``` rust,norun
60+ use std::thread;
61+ use std::sync::atomic::{AtomicUsize, Ordering};
62+ use std::sync::Arc;
63+
64+ let data = vec![1, 2, 3, 4];
65+
66+ let idx = Arc::new(AtomicUsize::new(0));
67+ let other_idx = idx.clone();
68+
69+ // `move` captures other_idx by-value, moving it into this thread
70+ thread::spawn(move || {
71+ // It's ok to mutate idx because this value
72+ // is an atomic, so it can't cause a Data Race.
73+ other_idx.fetch_add(10, Ordering::SeqCst);
74+ });
5775
5876if idx.load(Ordering::SeqCst) < data.len() {
5977 unsafe {
You can’t perform that action at this time.
0 commit comments