rust-lang / rust-lang/rust-clippy
Warn on probably incorrect usage of atomic `atomic.store(atomic.load() op n)`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
If the user uses .load(), and then some operation (that exists as a fetch_* operation on the atomic value, ignoring fetch_update), and then stores that value back into the atomic variable, suggest using the fetch_* operation instead.
If the user used two different atomic orderings, take the stronger of the two (Using AcqRel if Acquire + Release is used).
Suggesting fetch_update for more complex cases is out of scope for this lint, I think it's best to keep it as just fetch_add, fetch_and, fetch_max, fetch_min, fetch_nand, fetch_or, fetch_sub, fetch_xor.
Unclear to me if this is correctness or just suspicious. I'd be inclined to go with correctness because it seems highly unlikely this is intentional.
Lint Name
atomic_load_op_store
Category
correctness, suspicious
Advantage
- Remove the chance of data corruption by multiple threads loading at the same time before the store
Drawbacks
fetch_* operations cannot check for overflow, so this is a slight change to behavior with overflow checks enabled.
There also might be some situations where this is intended (although I cannot think of any). The assembly for the fetch_add operation does need a lock prefix, whereas the load/store does not, so if conflicts are unlikely/fine, load/store might be faster.
Example
let atomic = AtomicI32::new(0);
atomic.store(atomic.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
Could be written as:
let atomic = AtomicI32::new(0);
atomic.fetch_add(1, Ordering::Relaxed);
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the atomic_load_op_store specification and its Rust example, then locate the existing Clippy lint infrastructure for atomic operations. Implement detection for the listed fetch_* equivalents and combine differing orderings as described. Verify the example is suggested while fetch_update and overflow-check behavior remain out of scope.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100