Last active
April 17, 2016 03:13
-
-
Save NickStrupat/2c75fe7d3d67a84340bb to your computer and use it in GitHub Desktop.
A fast mutex struct
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
using System; | |
using System.Threading; | |
struct LightMutex { | |
private volatile Int32 inUse; | |
public void Lock() { | |
var spinWait = new SpinWait(); | |
while (Interlocked.Exchange(ref inUse, 1) == 1) | |
spinWait.SpinOnce(); | |
} | |
public void Unlock() { | |
Interlocked.Exchange(ref inUse, 0); | |
} | |
public void Guard(Action body) { | |
Lock(); | |
try { | |
body(); | |
} | |
finally { | |
Unlock(); | |
} | |
} | |
public T Guard<T>(Func<T> body) { | |
Lock(); | |
try { | |
return body(); | |
} | |
finally { | |
Unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment