-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Background and motivation
We have a few flags fields in the compiler that can be set by multiple threads, used as part of our symbol models. As we avoid locks whenever possible, we generally use a loop on Interlocked.CompareExchange, under the assumption it will succeed eventually or the value will have been computed and set by some other thread. However, because CompareExchange only supports int, long, uint, and ulong integer values, these fields must be at least 1 int wide. This doesn't sound like much, but as the compiler needs to load many, many symbols, those few extra bits can add up. I'd like to be able to use bytes where possible for these values. I only really want byte/ushort overloads, but added the signed variants for completeness.
API Proposal
namespace System.Threading
{
public static class Interlocked
{
public static byte CompareExchange(ref byte location1, byte value, byte comparand);
public static sbyte CompareExchange(ref sbyte location1, sbyte value, sbyte comparand);
public static short CompareExchange(ref short location1, short value, short comparand);
public static ushort CompareExchange(ref ushort location1, ushort value, ushort comparand);
}
}API Usage
public static bool Set(ref byte flags, byte toSet)
{
byte oldState, newState;
do
{
oldState = flags;
newState = oldState | toSet;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(byte flags, newState, oldState) != oldState);
return true;
}Alternative Designs
No response
Risks
No response