A counter can pass a test when two workers happen to run one after another and still lose an update when their reads overlap. Make that difference reproducible by putting a test barrier between the read and the write. Then replace the whole update with an atomic operation and check the result under overlapping execution.
This tutorial uses two dedicated threads and the base class library. Both complete programs were compiled and run as .NET 10 console applications in a pinned Linux SDK container without network access on 4 November 2026. The checks demonstrate particular interleavings and exit paths; they are not a benchmark or an exhaustive concurrency proof.
Choose the interleaving before choosing the fix
Microsoft’s managed threading guidance explains why incrementing a shared field involves separate read, modify, and write steps. Another thread can change the field between those steps. The test below expands the update into a local snapshot and a write so it can put a rendezvous exactly at that boundary.
| Schedule | What the workers do | Asserted total |
|---|---|---|
| Ordered control | Worker A reads and writes, then worker B reads and writes. | 2 |
| Forced overlap | Both read zero before either writes one. | 1 |
| Atomic fix | Both reach the barrier, then each performs one atomic increment. | 2 |
Barrier.SignalAndWait waits for the registered participants to arrive. Here, the broken path places that wait after taking the snapshot. The fixed path places it before the indivisible increment. There is no stale snapshot to write back in the fixed path.
Run the ordered control, forced failure, and fix
Create a console project with the .NET 10 SDK:
dotnet new console --name ControlledRace --framework net10.0
cd ControlledRace
Replace all of Program.cs with this complete program, then run dotnet run. It repeats all three schedules 50 times. Each unexpected result throws; success output is printed only after every round finishes.
using System;
using System.Collections.Concurrent;
using System.Threading;
for (int round = 0; round < 50; round++)
{
Check(Run(atomic: false, overlap: false), 2);
Check(Run(atomic: false, overlap: true), 1);
Check(Run(atomic: true, overlap: true), 2);
}
Console.WriteLine("50 rounds: ordered read/write = 2");
Console.WriteLine("50 rounds: overlapping read/write = 1");
Console.WriteLine("50 rounds: overlapping atomic increments = 2");
Console.WriteLine("300 workers joined; 300 cleanup paths completed");
static void Check(int actual, int expected)
{
if (actual != expected)
throw new InvalidOperationException($"Expected {expected}, got {actual}");
}
static int Run(bool atomic, bool overlap)
{
int value = 0, finished = 0;
var errors = new ConcurrentQueue<Exception>();
var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var rendezvous = new Barrier(2);
Thread[] workers = { new Thread(Work), new Thread(Work) };
int started = 0;
try
{
foreach (Thread worker in workers)
{
worker.IsBackground = true;
worker.Start();
started++;
// In the ordered control, finish one worker before starting the next.
if (!overlap && !worker.Join(5000))
throw new TimeoutException("Ordered worker did not finish");
}
foreach (Thread worker in workers)
if (!worker.Join(5000))
throw new TimeoutException("Worker did not finish");
if (!errors.IsEmpty) throw new AggregateException(errors);
Check(finished, 2);
return value;
}
finally
{
deadline.Cancel();
bool drained = true;
for (int i = 0; i < started; i++)
drained &= workers[i].Join(5000);
// Never dispose a barrier while a worker might still be using it.
if (!drained) throw new TimeoutException("Cleanup could not join workers");
rendezvous.Dispose();
deadline.Dispose();
}
void Meet()
{
if (!rendezvous.SignalAndWait(2000, deadline.Token))
throw new TimeoutException("Missing barrier participant");
}
void Work()
{
try
{
deadline.Token.ThrowIfCancellationRequested();
if (atomic)
{
Meet();
Interlocked.Increment(ref value);
}
else
{
int snapshot = value;
if (overlap) Meet(); // Both reads finish before either write.
value = snapshot + 1;
}
}
catch (Exception error)
{
errors.Enqueue(error);
deadline.Cancel();
}
finally
{
Interlocked.Increment(ref finished);
}
}
}
Expected stdout:
50 rounds: ordered read/write = 2
50 rounds: overlapping read/write = 1
50 rounds: overlapping atomic increments = 2
300 workers joined; 300 cleanup paths completed
The two broken paths execute the same read and write. Joining the first worker before starting the second gives the ordered control a total of two. In the overlapping path, both snapshots must exist before the barrier opens. Each snapshot is zero, so both writes store one. This deliberately instrumented model demonstrates the lost-update mechanism; it does not claim to intercept the individual machine instructions of an ordinary increment.
The fix uses Interlocked.Increment, whose contract makes the increment atomic. After the barrier opens, either worker may increment first; both increments still contribute to the final total. The barrier remains test instrumentation, while the atomic operation protects the counter. Retaining the barrier in application code would impose an unrelated requirement that a second participant arrive.
Keep the test bounded. Each barrier wait has a two-second timeout and observes a five-second cancellation deadline for its run. Worker exceptions are collected and cancel the shared deadline. The main thread checks joins, and the finally block cancels outstanding waits and joins every started worker before disposing the barrier. If cleanup cannot join a worker, the program throws rather than reporting success or disposing a barrier still in use. These are finite cooperative waits, not a promise of exact wall-clock termination under every host failure.
The first program checks 150 runs and 300 worker cleanup paths. The atomic runs are repeated regression checks of this scenario. Their success does not establish correctness for a counter that also resets, overflows, or participates in a multi-field business rule.
Test the harness’s timeout and cancellation paths
A synchronization test can hang because its own participant count is wrong. Run the next program separately by replacing Program.cs. It deliberately registers two participants while supplying one caller, then checks a separate barrier with a token canceled before the call.
using System;
using System.Threading;
for (int round = 0; round < 10; round++)
{
// Register two participants, but deliberately supply only this caller.
using (var missingPeer = new Barrier(2))
{
if (missingPeer.SignalAndWait(20, CancellationToken.None))
throw new InvalidOperationException("Missing participant was ignored");
}
using var canceled = new CancellationTokenSource();
canceled.Cancel();
using var canceledBarrier = new Barrier(2);
bool cancellationObserved = false;
try
{
canceledBarrier.SignalAndWait(2000, canceled.Token);
}
catch (OperationCanceledException error) when (
error.CancellationToken == canceled.Token)
{
cancellationObserved = true;
}
if (!cancellationObserved)
throw new InvalidOperationException("Expected cancellation");
}
Console.WriteLine("10 rounds: missing participant returned false");
Console.WriteLine("10 rounds: pre-canceled token threw OperationCanceledException");
Console.WriteLine("All barrier calls returned before disposal");
Expected stdout:
10 rounds: missing participant returned false
10 rounds: pre-canceled token threw OperationCanceledException
All barrier calls returned before disposal
The timed, cancellable SignalAndWait overload reports a timeout with false and cancellation with OperationCanceledException. The first program converts a timeout into an explicit test failure. This second program expects the timeout and verifies cancellation separately. It checks pre-cancellation; it does not exercise cancellation racing with a barrier phase completing. Every call has exited before its barrier is disposed.
Adapt the test to a real race
- Write down the invariant first: two completed increments must add two to the total.
- Locate the boundary between observing shared state and committing a change. Put test-only coordination there to force the competing observation.
- Keep an ordered control. A green result with serialized workers shows why a convenient schedule can hide the defect.
- Fix the complete operation. A single atomic increment fits this counter; a decision involving several fields needs a design covering the whole invariant.
- Keep a bounded wait, cancellation route, and worker drain in the test harness. Record a failed rendezvous as a harness failure, not as evidence that the counter is correct.
A lost update and a deadlock need different observations: this counter finishes with the wrong total, while a deadlock prevents progress. Continue with reproducing a two-lock deadlock and fixing lock ordering for a bounded progress test, or CancellationToken propagation across application layers for carrying cancellation into real operations.