skip to content

A C# rate counter runs _hits++ on many threads and loses counts; why doesn't marking the field volatile fix it, and when is Interlocked enough instead of lock?

level: seniorimportance: should knowfreq 55%

answer

  1. one statement, three steps
  2. ordering is not atomicity
  3. a static class of atomic operations
  4. compare, then swap, then retry
  5. several fields need a lock

basics

~20 s

_hits++ is a load, an add and a store, so two threads can store the same value. volatile only limits how single reads and writes are reordered; Interlocked.Increment makes the update atomic. Fields that must change together need lock.

solid answer

~40 s

`_hits++` compiles to a load, an add and a store; two threads can both load 41 and both store 42. `volatile` does not change that: Microsoft's documentation says it gives no atomicity for operations other than assignment; it only excludes the field from certain optimizations that reorder individual reads and writes. `Interlocked.Increment(ref _hits)` performs the read-modify-write as one atomic operation and returns the new value; `Interlocked.Add`, `Exchange` and `CompareExchange` cover adding, swapping and conditional updates, and `Interlocked.Read` loads a `long` atomically. Interlocked is enough when the invariant lives in **one** variable. When two fields must agree, such as a count and a window start, or a check must stay true until the update, use `lock`. `volatile` cannot even be applied to a `long` or `double` field (error CS0677).

code

csharp · 31 lines
csharp
using System.Threading;

var stats = new RateStats();
var workers = new Thread[8];
for (int i = 0; i < workers.Length; i++)
{
    workers[i] = new Thread(() =>
    {
        for (int n = 0; n < 1_000_000; n++) stats.Hit();
    });
    workers[i].Start();
}
foreach (var w in workers) w.Join();

Console.WriteLine($"plain ++     : {stats.Racy}");
Console.WriteLine($"volatile ++  : {stats.VolatileRacy}");
Console.WriteLine($"Interlocked  : {Volatile.Read(ref stats.Safe)}");

class RateStats
{
    public int Racy;
    public volatile int VolatileRacy;
    public int Safe;

    public void Hit()
    {
        Racy++;                          // read, add, write: three steps
        VolatileRacy++;                  // still three steps
        Interlocked.Increment(ref Safe); // one atomic read-modify-write
    }
}

go deeper

for a junior

Recall that ++ on a shared field is not thread-safe and that Interlocked.Increment is the one-line fix for a single counter.

for a middle

Explain the load, add, store split, what volatile constrains and what it does not, and which Interlocked method returns the new value versus the original one.

for a senior

Decide per invariant: one location gets Interlocked or a compare-and-swap loop, anything spanning fields gets lock, and volatile is kept to a lone flag.

for a principal

Set the review bar: lock-free code needs a reason and a test that runs many threads, because a lost update never throws and shows up only as wrong numbers.

## Why ++ loses updates An in-process rate counter that every request thread bumps looks harmless: ```csharp public int Hits; public void Hit() => Hits++; ``` The statement `Hits++` is not one operation. The compiled code does three: 1. **Load** the current value of `Hits` into a register. 2. **Add** one to it. 3. **Store** the result back into the field. If two threads both load 41 before either stores, both store 42 and one hit disappears. Nothing throws; the count is just low. In the example on this page, eight threads each doing a million increments ended with under 3 million on the plain field instead of 8 million, a different number on every run. ## What volatile does, and what it does not `volatile` is a field modifier. Microsoft's language reference says it excludes the field from certain optimizations by the compiler, the runtime and the hardware, and then lists what it does **not** do: - It provides **no atomicity for operations other than assignment**, so `volatileField++` is still load, add, store. In the same runs the `volatile int` counter lost about as many updates as the plain one. - It does not prevent race conditions, and it gives no ordering guarantees for other memory operations. - On a multiprocessor, a volatile read is not guaranteed to see the latest value written by another processor at that instant. - It applies only to fields of certain types: reference types, `int`, `bool`, `float` and the other simple types up to 32 bits, enums based on them, `IntPtr` and `UIntPtr`. `public volatile long Total;` is error CS0677, "'S.Total': a volatile field cannot be of the type 'long'". Its legitimate use is narrow: a single flag written by one thread and polled by another, such as a stop request. The reference itself recommends `Interlocked`, `lock` or the `Volatile` class (`Volatile.Read` and `Volatile.Write`) in most cases. ## The Interlocked toolbox `System.Threading.Interlocked` is a static class whose methods each perform one atomic operation on a variable passed by `ref`: | Method | What it does atomically | Returns | |---|---|---| | `Increment` / `Decrement` | add or subtract one | the new value | | `Add` | add an amount (`int`, `long`, and unsigned variants) | the new value | | `Exchange` | store a value | the original value | | `CompareExchange` | store only if the current value equals a comparand | the original value | | `Read` | load a 64-bit value | the loaded value | | `And` / `Or` | combine bits | the original value | `Interlocked.Read` matters for `long` because, as the `volatile` reference notes, plain reads and writes of a `long` can't be guaranteed to be atomic; `Exchange` and `CompareExchange` also have reference-type and generic overloads, which makes swapping in a new configuration object a single atomic step. ## Compare-and-swap loops When the new value depends on the old one in a way no single method covers, such as recording a peak, read the field, compute, and publish with `CompareExchange`, retrying if another thread got there first: ```csharp int seen = Volatile.Read(ref peak); while (observed > seen) { int actual = Interlocked.CompareExchange(ref peak, observed, seen); if (actual == seen) return; // our write won seen = actual; // someone else changed it; re-check } ``` The loop never blocks, but it can spin under heavy contention, and it only works because the whole state is one `int`. ## When to step up to lock Interlocked operations protect **one memory location**. Reach for `lock` when: - two or more fields must stay consistent, such as a hit count and the start of its time window that resets together; - a check must stay true until the update, such as "under the limit, then increment" across fields; - the update involves a collection or any object that is not itself thread-safe; - the lock-free version is harder to review than the cost it saves. A useful rule in code review: one counter or one reference swap, `Interlocked`; anything with an invariant spanning two places, `lock`; `volatile`, only for a lone flag, and usually `Volatile.Read` and `Volatile.Write` say the same thing more visibly. One more trap: `lock` and `Interlocked` do not coordinate. A field bumped with `Interlocked.Increment` in one method and with `++` inside a `lock` in another is still racy, because the lock does not stop the atomic operation and the atomic operation ignores the lock. Pick one mechanism per field and use it at every access.

  • When is a volatile field actually the right tool in C#?
    For a single value written by one thread and read by others where only visibility and ordering of that one read or write matter, such as a stop flag a worker polls. It never makes a read-modify-write atomic. The language reference also points to `Volatile.Read` and `Volatile.Write`, which make the intent visible at each access site.
  • How would you track a maximum observed value atomically without a lock?
    Read the field, and while the observed value is larger, call `Interlocked.CompareExchange(ref peak, observed, seen)`. If it returns `seen`, your write won; otherwise it returns the value another thread stored, and you re-check against that. It works because the whole state is one `int`.

  • Marking the counter volatile makes _hits++ atomic.
  • Interlocked.Increment returns the value before the increment.
  • Interlocked can keep two related fields consistent if each uses it.
  • A volatile long is fine for a 64-bit counter.
  • Lost increments always throw an exception you can catch.