Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
Tutorial

High-Performance Interlocked Operations vs Locks in C#: When to use CompareExchange [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Vertegenwoordiger: 47
Datum van deelname: Feb 2018
Berichten: 17
Bedankt: 75
1 maanden geleden ยท Jul 3, 2026 9:41 AM
#1

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!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Vertegenwoordiger: 103
Datum van deelname: Apr 2018
Berichten: 40
Bedankt: 24
1 maanden geleden ยท Jul 3, 2026 1:31 PM
#2

Interlocked.CompareExchange loops (CAS loops) are the foundation of lock-free data structures in .NET.

profiler_pat
Performance Hunter
MEMBER
Vertegenwoordiger: 146
Datum van deelname: Aug 2019
Berichten: 33
Bedankt: 31
1 maanden geleden ยท Jul 4, 2026 1:58 AM
#3

Much faster than lock(obj) when contention is short and infrequent.