Skip to content

Instantly share code, notes, and snippets.

@badamczewski
Last active August 29, 2015 14:19
Show Gist options
  • Save badamczewski/74c983803b6e9779426c to your computer and use it in GitHub Desktop.
Save badamczewski/74c983803b6e9779426c to your computer and use it in GitHub Desktop.
Very simple MCL lock implementation.
#region Licence
/*
Copyright (c) 2011-2015 Bartosz Adamczewski (Bax Services)
MCSLock is distributed WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
public class MCSLock
{
public class Node
{
public int locked;
public Node next;
public Node()
{
}
}
public Node mcs;
[ThreadStatic]
public static Node local;
public MCSLock()
{
mcs = new Node();
}
public void Acquire()
{
local = new Node();
local.locked = 1;
//do an atomic xchange, CAS is not needed since we need to compare it
//against org value and take action. Thus this variant is much faster.
var org = Interlocked.Exchange(ref mcs.next, local);
//lock is owned.
if (org == null)
return;
//someone was holding the lock ;(, we need to fix the pointers.
else
{
//point the lock owner to our Node, so we can be notified that he's done.
Interlocked.Exchange(ref org.next, local);
int backoff = 0;
//start spinlock
while (org.next.locked == 1)
{
Thread.MemoryBarrier();
//do some initial backoff.
if(backoff++ > 10)
Thread.Sleep(0);
}
//we own the lock.
return;
}
}
public void Release()
{
if (Interlocked.CompareExchange(ref mcs.next, null, local) != local)
{
//we failed to set null on the queue, that means other threads are waiting on a lock
//so take the next waiting thread and unlock it.
//this is still not safe though if Interlocked.Exchange(ref org.next, local); is not yet called
//then local.next will be null, so spin a few cycles.
while (local.next == null) { Thread.MemoryBarrier(); }
Interlocked.Exchange(ref local.next.locked, 0);
}
//No contention, super duper happy path. release.
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment