1 か月前 · Jul 3, 2026 9:41 AM
Implementing lock-free updates using Interlocked.CompareExchange:
CSHARP
public static void UpdateMax(ref int target, int newValue)
{
int current = target;
while (newValue > current)
{
int previous = Interlocked.CompareExchange(ref target, newValue, current);
if (previous == current) break; // Successful atomic update!
current = previous;
}
}Executes with a single atomic hardware CMPXCHG instruction on x86, avoiding OS kernel thread suspension and context switches!