Middle · Explain · Interlocked covers one operation at a time

Why is an Interlocked increment stronger than separate volatile reads and writes but weaker than a multi-field transaction?

Think through your answer before opening the explanation.

Runtime & concurrency

Reveal answer and reasoning

Interlocked.Increment performs the read-modify-write as one atomic operation on its specified location. Separate Volatile.Read and Volatile.Write calls can each obey their own ordering rules while two workers still read the same old value and overwrite the same incremented result. The lesson's barrier controls that interleaving rather than relying on a random stress-run failure.

Atomicity does not automatically extend to neighboring fields, callbacks, or external effects. Two individually atomic counters can temporarily violate a relationship a reader expects to observe as one snapshot. A common wrong answer calls every statement around an Interlocked call thread-safe or assumes volatile makes a compound increment indivisible. Define the actual invariant and reader protocol, then use a lock, one immutable published state, or another operation matching that invariant.

Durability and exactly-once work remain different concerns from local atomic memory updates.

What a strong answer covers

  • Interlocked covers one specified operation.
  • Volatile does not combine read and write into atomic increment.
  • Larger invariants require a larger protocol.

Common pitfall

Extending one atomic operation's guarantee to an entire surrounding workflow.

Follow-up questions

  1. How would readers observe two related counters consistently?
  2. Why is the barrier useful in the negative fixture?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions