Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock Free Concurrent Queue

Tags:

c#

lock-free

This code snippet is from ConcurrentQueue implementation given from here.

internal bool TryPeek(out T result) 
{
    result = default(T); 
    int lowLocal = Low;
    if (lowLocal > High)
        return false;
    SpinWait spin = new SpinWait(); 
    while (m_state[lowLocal] == 0)
    { 
        spin.SpinOnce(); 
    }
    result = m_array[lowLocal]; 
    return true;
}

Is it really lock-free instead of spinning?

like image 406
Hamlet Hakobyan Avatar asked Dec 03 '25 05:12

Hamlet Hakobyan


2 Answers

Spinning is a lock. This is stated in MSDN, Wikipedia and many other resources. It's not about word. Lock-free is a guarantee. It doesn't mean that the code shouldn't use lock statement. Algorithm is lock-free if there is guaranteed system-wide progress. I don't see any difference between this code and the code using locks. The only difference is that the spin uses busy wait and thread yielding instead of putting thread in a sleep mode. I don't see how this guarantees system-wide process, so personally I think that this is not a lock-free implementation. At least not this function.

like image 175
axe Avatar answered Dec 04 '25 19:12

axe


Lock free means not using locks. Spinwaiting is not locking. There are a number of methods of synchronizing access to data without using locks. Performing spin waits is one (of many) options. Not all lock-free code will use spin-waits.

like image 44
Servy Avatar answered Dec 04 '25 19:12

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!