Skip to content

Commit daed96b

Browse files
committed
Adding atomics thread safety paragraph with an example
1 parent 74fb069 commit daed96b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/concurrency.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,27 @@ fn main() {
106106
}
107107
```
108108

109+
r[concurrency.atomics.thread-safety]
110+
Atomic operations are guaranteed to be indivisible: no other thread can observe a value half-written or perform a conflicting update in the middle of an atomic operation. Correct use of atomic types can prevent [data races], but misuse may still cause higher-level concurrency bugs such as deadlocks or livelocks.
111+
112+
```rust
113+
use std::sync::atomic::{AtomicUsize, Ordering};
114+
use std::thread;
115+
116+
fn main() {
117+
static VALUE: AtomicUsize = AtomicUsize::new(0);
118+
119+
let t1 = thread::spawn(|| VALUE.store(1, Ordering::Relaxed));
120+
let t2 = thread::spawn(|| VALUE.store(2, Ordering::Relaxed));
121+
122+
t1.join().unwrap();
123+
t2.join().unwrap();
124+
125+
// VALUE is guaranteed to be either 1 or 2 — never a corrupted mix.
126+
println!("{}", VALUE.load(Ordering::Relaxed));
127+
}
128+
```
129+
109130
[concurrent programs]: glossary.md#concurrent-program
110131
[data races]: glossary.md#data-race
111132
[`Send`]: special-types-and-traits.md#send

0 commit comments

Comments
 (0)