C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
What are Memory Barriers, volatile, and Interlocked operations in the .NET Memory Model?
senior LevelCode ExamplecsharpConcurrency
In Simple Words:
Interlocked: Hardware-level atomic operations (CAS / atomic increment). Guarantees thread-safe lock-free mutation on single CPU cycles without locking.volatile: Informs the JIT compiler and CPU cache coherence controllers that reads must have acquire semantics and writes must have release semantics, preventing stale reads across CPU caches.- Memory Barrier (
Thread.MemoryBarrier()): Enforces CPU instruction pipeline boundaries, ensuring all preceding reads/writes complete before subsequent reads/writes begin.
csharp
private long _requestCounter;
public void IncrementRequests() {
// Lock-free hardware atomic increment:
Interlocked.Increment(ref _requestCounter);
}