Where is InterlockedRead?

interlocked, multithreading, winapi

Solution

The normal way of implementing this is to use a compare-exchange operation (e.g. `InterlockedCompareExchange64`) where both values are the same. I have a sneaking suspicion this can be performed more efficiently than an add of 0 for some reason, but I have no evidence to back this up.

Interestingly, .NET's `Interlocked` class didn't gain a `Read` method until .NET 2.0. I believe that `Interlocked.Read` is implemented using `Interlocked.CompareExchange`. (Note that the documentation for `Interlocked.Read` strikes me as somewhat misleading - it talks about atomicity, but not volatility, which means something very specific on .NET. I'm not sure what the Win32 memory model guarantees about visibility of newly written values from a different thread, if anything.)

Problem

Win32 api has a set of InterlockedXXX functions to atomically and synchronously manipulate simple variables, however there doesn't seem to be any InterlockedRead function, to simply retrive the value of the variable. How come? MSDN says that: Simple reads and writes to properly-aligned 32-bit variables are atomic operations but adds: However, access is not guaranteed to be synchronized. If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation. Which means, as I understand it, that a simple read operation of a variable can take place while another, say, InterlockedAdd operation is in place. So why isn't there an interlocked function to read a variable? I guess the value can be read as the result InterlockedAdd-ing zero, but that doesn't seem the right way to go.

Original source