Skip to content

Commit 128605f

Browse files
committed
Adding atomics usage sentence with an example test
1 parent 851e745 commit 128605f

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/concurrency.md

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ fn main() {
107107
```
108108

109109
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.
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.
111111

112112
```rust
113113
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -122,7 +122,7 @@ fn main() {
122122
t1.join().unwrap();
123123
t2.join().unwrap();
124124

125-
// VALUE is guaranteed to be either 1 or 2 never a corrupted mix.
125+
// VALUE is guaranteed to be either 1 or 2, never a corrupted mix.
126126
println!("{}", VALUE.load(Ordering::Relaxed));
127127
}
128128
```
@@ -145,6 +145,33 @@ The following table lists the atomic types and the corresponding primitive types
145145
| `usize` | [`core::sync::atomic::AtomicUsize`] |
146146
| `*mut T` | [`core::sync::atomic::AtomicPtr<T>`] |
147147

148+
r[concurrency.atomics.usage]
149+
Atomic types are [`Sync`], meaning references to them can be safely shared between threads. Using atomic operations correctly may require careful reasoning about memory ordering.
150+
151+
```rust
152+
use std::sync::atomic::{
153+
AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64,
154+
AtomicIsize, AtomicU8, AtomicU16, AtomicU32, AtomicU64,
155+
AtomicUsize,
156+
};
157+
158+
fn assert_sync<T: Sync>() {}
159+
160+
fn main() {
161+
assert_sync::<AtomicBool>();
162+
assert_sync::<AtomicI8>();
163+
assert_sync::<AtomicI16>();
164+
assert_sync::<AtomicI32>();
165+
assert_sync::<AtomicI64>();
166+
assert_sync::<AtomicIsize>();
167+
assert_sync::<AtomicU8>();
168+
assert_sync::<AtomicU16>();
169+
assert_sync::<AtomicU32>();
170+
assert_sync::<AtomicU64>();
171+
assert_sync::<AtomicUsize>();
172+
}
173+
```
174+
148175
[concurrent programs]: glossary.md#concurrent-program
149176
[data races]: glossary.md#data-race
150177
[`Send`]: special-types-and-traits.md#send

0 commit comments

Comments
 (0)