Middle · Trace · Interlocked covers one operation at a time

Trace both increments and the successful integer CompareExchange return value.

Think through your answer before opening the explanation.

Runtime & concurrency

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

int count = 0;
Console.WriteLine($"first:{Interlocked.Increment(ref count)}");
Console.WriteLine($"second:{Interlocked.Increment(ref count)}");
int observed = Interlocked.CompareExchange(ref count, 5, 2);
Console.WriteLine($"observed:{observed}");
Console.WriteLine($"current:{count}");
Reveal answer and reasoning

The output is first:1, second:2, observed:2, and current:5. Each Interlocked.Increment returns its new value. CompareExchange then sees the expected integer two, replaces it with five, and returns the old observed value two. That return is not the new value and is not itself a success boolean; the final explicit read shows what is stored afterward.

A common wrong trace prints observed five because it assumes every atomic update returns the new state. Another assumes the surrounding operations form one transaction. This portable code contains one sequential integer location and no worker overlap. The desktop fixture separately demonstrates a controlled split lost update and a four-hundred atomic total. Those tests answer different questions, and neither makes unrelated fields, effects, or arbitrary caller code atomic simply because this baseline exchange succeeded.

What a strong answer covers

  • Increment returns each new value.
  • CompareExchange returns the prior observation.
  • The successful exchange stores five.

Common pitfall

Confusing CompareExchange's old-value return with Increment's new-value return.

Follow-up questions

  1. What changes if the expected value is three?
  2. How would you derive a success check from the returned observation?

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