Locks and atomic operations
Locks and atomic operations
Mutual exclusion protects a critical section from concurrent entry by workers using the same lock. Atomic operations update one location indivisibly; they do not automatically protect relationships between several fields. Visibility and ordering are distinct from atomicity. A lock establishes synchronization at entry and exit, while volatile reads/writes impose specific acquire/release ordering without turning compound operations into transactions.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Protect two inventory fields with one lock
The invariant is available + reserved = 10. All reads and updates of these fields use one private System.Threading.Lock. It is a modern .NET 9+ type supported by C# 13+.
using System;using System.Threading;using System.Threading.Tasks;var gate = new Lock();int available = 10, reserved = 0;Parallel.For(0, 6, new ParallelOptions { MaxDegreeOfParallelism = 2 }, _ =>{ lock (gate) { if (available == 0) return; available--; reserved++; }});lock (gate){ Console.WriteLine($"{available},{reserved}"); Console.WriteLine(available + reserved);}The check and both updates are within the critical section. For an ordinary object lock, C# uses Monitor semantics; for a statically typed Lock it uses its special scope mechanism. Do not cast Lock to object to mix locking mechanisms. Do not await in a lock body.
Expected observation (reasoned, not executed):
4,610Use an atomic increment and conditional update
Choose Interlocked for an independent scalar. CompareExchange changes the location only when its current value equals the comparand and returns the previous value.
using System;using System.Threading;using System.Threading.Tasks;int count = 0;Parallel.For(0, 8, new ParallelOptions { MaxDegreeOfParallelism = 2 }, _ => Interlocked.Increment(ref count));Console.WriteLine(count);int previous = Interlocked.CompareExchange(ref count, 10, 8);Console.WriteLine($"{previous},{count}");Each increment is atomic. The conditional replacement succeeds after the loop because count is 8. This operation alone cannot atomically maintain a second independent field.
Expected observation (reasoned, not executed):
88,10Publish a value with acquire/release ordering
One producer writes a payload, then publishes a flag. The consumer performs a single volatile read; it may arrive before publication. No spin loop, time-based assertion or dependence on a particular ordering.
using System;using System.Threading;using System.Threading.Tasks;int payload = 0, ready = 0;Task writer = Task.Run(() =>{ payload = 42; Volatile.Write(ref ready, 1);});Task<int?> reader = Task.Run<int?>(() => Volatile.Read(ref ready) == 1 ? payload : null);await writer;int? observed = await reader;Console.WriteLine(observed is null or 42);Console.WriteLine(payload);If the reader sees the published flag, acquire/release ordering makes the preceding payload write visible. It may instead see zero and return null. The check accepts either legal outcome; after awaiting the writer the payload is 42. A single run does not prove a memory model or test all reorderings.
Expected observation (reasoned, not executed):
True42Common mistakes and design trade-offs
Use one private lock for an invariant, acquire multiple locks in a documented order, and avoid slow external work while holding a lock. Monitor.TryEnter can bound waiting but must release only after successful entry. Mutex can coordinate across processes where supported; it has different costs and lifetime semantics. ConcurrentDictionary offers atomic individual operations such as TryAdd; composing separate reads and writes may race. Avoid using volatile as a general replacement for locks.
Apply the concept
Design a reservation service with total stock 5 and two workers each asking for 4 units. State the protected invariant and possible outcomes. Explain why two Interlocked updates alone are insufficient.
Check your work: Exactly one request can succeed if stock begins at 5. Final available=1, reserved=4. Protect the check and both changes in one lock; two independent atomic operations can expose or violate a multi-field invariant.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Locks and atomic operations — knowledge check
Apply the lesson concepts to the following scenarios.
What does lock protect when all callers follow the same protocol?
What does Interlocked.Increment guarantee?
CompareExchange changes 8 to 10 when comparand is 8. What does it return?
What can the single volatile reader see in the publication example?
Why not use two independent locks for the inventory check and update?