C# Reference ยท Async and Concurrency
Volatile and memory barriers
Explain the volatile keyword, Volatile.Read and Volatile.Write, Thread.MemoryBarrier and the .NET memory model: visibility, reordering and safe publication.
Compilers, the JIT and CPUs are allowed to reorder memory reads and writes, and to cache values in registers, as long as a single thread cannot tell the difference. Another thread can tell. Without synchronization it may see updates late, in a different order, or (in a tight loop) never.
The tools that restrain this are the volatile keyword, Volatile.Read and Volatile.Write, full fences like Thread.MemoryBarrier(), and every synchronization primitive (lock, Interlocked, Task start and completion, Thread.Start and Join). Most code should just use lock or higher-level types; these low-level pieces matter for flags and carefully written lock-free code.
private volatile bool _stop; // thread A: _stop = true; // thread B: while (!_stop) { ... }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
The memory model in practice
What volatile does. Reading a volatile field has acquire semantics: no later read or write can be moved before it. Writing one has release semantics: no earlier read or write can be moved after it. Together they make the "write data, then set flag" / "check flag, then read data" pattern work.
What it does not do. It does not make x++ atomic, does not order a volatile write before a later volatile read (a store followed by a load can still be reordered), and gives no protection to several fields at once. Use Interlocked or lock for those.
Volatile.Read and Volatile.Write apply the same acquire and release rules to one access, and work on any field, array element or local, so you can pay the ordering cost only where needed. Prefer them to the keyword in new code.
Thread.MemoryBarrier() and Interlocked.MemoryBarrier() are full fences: nothing moves across them in either direction. They are rarely needed because lock and Interlocked already include them.
Syntax
private volatile int _flag; // field modifier public static class Volatile { public static T Read<T>(ref T location); public static void Write<T>(ref T location, T value); public static int Read(ref int location); public static void Write(ref int location, int value); } Thread.MemoryBarrier();
| Name | Description |
|---|---|
location |
The variable to read or write. |
value |
The value to publish. |
Returns: Read returns the value read, with acquire semantics. Write returns nothing.
Errors: a volatile field must have a type that allows it: reference types, bool, byte, short, int, char, float, nint, enums with those underlying types. long and double fields cannot be volatile (use Volatile.Read/Write or Interlocked).
Usage notes
- Spin loops are the classic bug.
while (!_stop) { }on a plain field may never end in an optimized build, because the JIT is allowed to read_stoponce. Make it volatile, useVolatile.Read, or use aCancellationTokenorManualResetEventSlim. - Atomicity is separate from ordering. Reads and writes of
intand references are atomic;longis atomic on 64-bit processes. Compound operations are not. - Safe publication. An object is safely published to another thread if the reference is written with release semantics and read with acquire semantics (or through a
lock,Interlocked, static constructor,Lazy<T>orTask). Constructors alone do not guarantee that other threads see fully initialized fields. - x86 hides bugs. The processor already provides strong ordering, so missing barriers often work on x86 and fail on ARM. Write for the .NET memory model, not for your laptop.
- Do not build your own lock-free structures unless profiling shows a need; prefer
ConcurrentQueue<T>,Channel<T>and friends. volatileon arefor property is not possible; useVolatile.Read(ref _field)inside the property getter.
Related
- Interlocked, Monitor and lock, Race conditions, Lazy
- Lessons: Synchronization, Threads