I'm trying to set bit flags in a shared variable within a multithreaded .NET application, but couldn't find a parallell to the native InterlockedOr function in the managed Interlocked class. I've come up with the following code for performing a |= assignment, but the theoretical possibility of an infinite loop is making me uncomfortable:
long currentValue;
long updatedValue;
do
{
// Spin until successful update. Value must be read using Interlocked.Read()
// to be truly atomic on 32 bit systems (see MSDN).
currentFlags = Interlocked.Read(ref _currentFlags);
updatedValue = currentFlags | flag;
} while (currentFlags != Interlocked.CompareExchange(ref _currentFlags, updatedValue, currentFlags));
Can this be implemented in a safer way using only the functions built into the Interlocked class? I'd like to avoid a solution involving an explicit lock if possible.