Skip to content

Common Atomic

Ivan Kozhin edited this page Jun 19, 2020 · 4 revisions

Methods to performs atomic operations.

1. Swap

void Swap<T>(ref T item1, ref T item2)

Swaps values of two variables.

int a = 2, b = 5;
int tmp = a;
a = b;
b = tmp;

// With Saritasa extensions.
int a = 2, b = 5;
AtomicUtils.Swap(ref a, ref b);

2. SafeSwap

void SafeSwap<T>(ref T item1, ref T item2)

Swaps values of two variables. Thread-safe.

3. DoWithCAS

The thread-safe implementation CAS (Compare-And-Swap). Get the location variable from memory, perform an action on it and replace it. There are also override implementations for double and int. Here is an example of a thread-safe multiply method:

public static void InterlockedMultiplyInPlace(ref int x, int y)
{
    AtomicUtils.DoWithCAS(ref x, t => t * y);
}

Clone this wiki locally