Skip to content

Instantly share code, notes, and snippets.

@Monsoonexe
Last active November 25, 2022 19:05
Show Gist options
  • Save Monsoonexe/9831a7c7a9326de539af227d2b17fe56 to your computer and use it in GitHub Desktop.
Save Monsoonexe/9831a7c7a9326de539af227d2b17fe56 to your computer and use it in GitHub Desktop.
An atomic, lock-free, thread-safe counter for C#
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