Is id 1 - id atomic?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In normal code, id = 1 - id is not atomic. It looks like one statement, but at runtime it is a read-modify-write sequence, and other threads can observe or interleave with that sequence unless you use an atomic primitive or a lock.
Why the Expression Is Not Atomic by Default
The operation has three logical steps:
- Read the current value of
id. - Compute
1 - id. - Write the result back.
If two threads do this concurrently, they can both read the same old value and both write the same new value, which means one logical toggle is lost.
That is the classic shape of a race condition.
Example of the Problem
Suppose id starts at 0 and two threads execute id = 1 - id at the same time.
- Thread A reads
0. - Thread B reads
0. - Thread A writes
1. - Thread B writes
1.
If the intention was to toggle twice and end up back at 0, that did not happen. One update effectively disappeared.
How to Make the Toggle Atomic
If id is restricted to 0 and 1, an atomic XOR operation is often the cleanest solution.
For a binary value, XOR with 1 flips 0 to 1 and 1 to 0 atomically.
If the language or type does not offer a suitable atomic update, use a lock around the whole read-modify-write sequence.
Now the whole operation is protected as one critical section.
Atomic Syntax Versus Atomic Semantics
A common mistake is to equate "one source-code line" with "one atomic operation." Those are not the same thing. Atomicity is about what other threads can observe, not about how compact the code looks.
Even on hardware where aligned integer loads and stores are individually atomic, the combined read-modify-write still is not atomic unless you use a real atomic primitive designed for that purpose.
When Memory Ordering Matters
Sometimes you only need the toggle itself to be atomic, in which case relaxed ordering may be enough. In other cases, the toggle also coordinates visibility of other shared data, and then memory ordering becomes part of the design.
That is why concurrency questions are rarely solved by syntax alone. You need to know what the variable means in the larger synchronization protocol.
Common Pitfalls
- Assuming a short arithmetic assignment is automatically atomic because it fits on one line.
- Using a plain integer from multiple threads without synchronization.
- Fixing visibility with
volatileand assuming that also solves atomicity. It usually does not. - Implementing a binary toggle with compare-and-swap loops when a simpler atomic operation would do.
- Ignoring memory-ordering requirements when the variable coordinates more than just its own value.
Summary
- '
id = 1 - idis not atomic in ordinary shared-memory code.' - It is a read-modify-write sequence and can race with other threads.
- Use an atomic primitive such as
fetch_xor(1)for a binary toggle, or protect the statement with a lock. - One source-code statement does not imply one indivisible machine-level action.
- Atomicity and memory ordering should be chosen based on the synchronization role of the variable.
Related reading
- Is incrementing an int effectively atomic in specific cases?
- Is it a reasonable trade-off to use `sleep` in an asynchronous job?
- Is it an anti-pattern to use async/await inside of a new Promise constructor?
- Is it bad to use polling in Java?
- Is it dangerous to use synchronize in a non-VCL application?
- Is it legal to call the start method twice on the same Thread?
- Is it legal to initialize a thread_local variable in the destructor of a global variable?
- Is it legal to pass stdshared_future as a reference to functions?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.