Last active
November 25, 2022 19:05
-
-
Save Monsoonexe/9831a7c7a9326de539af227d2b17fe56 to your computer and use it in GitHub Desktop.
An atomic, lock-free, thread-safe counter for C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.CompilerServices; | |
using System.Threading; | |
/// <summary> | |
/// Thread-safe counter. | |
/// </summary> | |
internal struct AtomicCounter | |
{ | |
private int counter; | |
public AtomicCounter(int value) | |
{ | |
counter = value; | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public void Set(int x) | |
{ | |
Interlocked.Exchange(ref counter, x); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public int Add(int x) | |
{ | |
return Interlocked.Add(ref counter, x); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public int Sub(int x) | |
{ | |
return Interlocked.Add(ref counter, -x); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public int Increment() | |
{ | |
return Interlocked.Increment(ref counter); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public int Decrement() | |
{ | |
return Interlocked.Decrement(ref counter); | |
} | |
public int Value | |
{ | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
get => Interlocked.Add(ref counter, 0); | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
set => Interlocked.Exchange(ref counter, value); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public static implicit operator int(AtomicCounter a) => a.Value; | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public static AtomicCounter operator --(AtomicCounter a) | |
{ | |
Interlocked.Decrement(ref a.counter); | |
return a; | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public static AtomicCounter operator ++(AtomicCounter a) | |
{ | |
Interlocked.Increment(ref a.counter); | |
return a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment