Skip to content

Instantly share code, notes, and snippets.

@mirasrael
Created April 29, 2022 08:59
Show Gist options
  • Save mirasrael/bd637dca538d20eeb24aef9b0087b041 to your computer and use it in GitHub Desktop.
Save mirasrael/bd637dca538d20eeb24aef9b0087b041 to your computer and use it in GitHub Desktop.
Interlocked operations
public class Sample
{
private volatile int counter;
public void IncrementUnlocked() => this.counter = this.counter + 1;
public void IncrementLocked() { lock (this) { this.counter = this.counter + 1; }
public void IncrementInterlocked1() => Interlocked.CompareExchange(ref this.counter, this.counter + 1, this.counter);
public void IncrementInterlocked2()
{
while (Interlocked.CompareExchange(ref this.counter, this.counter + 1, this.counter) != this.counter)) { }
}
public void IncrementInterlocked3()
{
int oldValue;
do
{
oldValue = this.counter;
} while (Interlocked.CompareExchange(ref this.counter, oldCounter + 1, oldCounter) != oldCounter));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment