Is My Spin Lock Implementation Correct and Optimal?

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

void beginSpinLock(lock)

{
if(lock) loopFor(1 milliseconds);
else
{
lock = true;
return;
}

if(lock) loopFor(2 milliseconds);


else
{
lock = true;
return;
}

// important is that the part above never


// cause the thread to sleep.
// It is "burning" the time slice of this thread.
// Hopefully for good.

// some implementations fallback to OS lock mechanism


// after a few tries
if(lock) return beginLock(lock);
else
{
lock = true;
return;
}
}
If your implementation is not careful, you can fall on livelock, spending all CPU on the lock
mechanism.

Also see:

https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?

Summary:

Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU
usage will be low;

Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and
not on your calculation;

Starvation: situation where one procress never gets the chance to run; by pure bad luck or
by some of its property (low priority, for example);

Spinlock: technique of avoiding the cost waiting the lock to be freed.

You might also like