Created
April 29, 2022 08:59
-
-
Save mirasrael/bd637dca538d20eeb24aef9b0087b041 to your computer and use it in GitHub Desktop.
Interlocked operations
This file contains 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
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