Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Last active April 17, 2016 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/2c75fe7d3d67a84340bb to your computer and use it in GitHub Desktop.
Save NickStrupat/2c75fe7d3d67a84340bb to your computer and use it in GitHub Desktop.
A fast mutex struct
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