My name is Bartosz Adamczewski and this blog is all about programming on the NET platform and beyond. I'm focusing on two languages C# and F#, but also I'm planning to throw some SQL to the mix, and maybe Java + Android platform, and C++ as cherry on top.

Pages

Wednesday, August 22, 2012

Lock Free And SpinWait MSDN Example

If you have read about the new features in 4.0 then probably you stumbled on a SpinWait structure and a MSDN article and the example code it provides. Just for the sake of clarity and history should the article change in the future I present you the code:

The example presents a lock free stack that uses the new SpinWait to issue a SpinOnce() operation after a failed CAS (Interlocked.CompareExchange). This is done to supposedly improve performance of code by doing a spin wait, but in my honest opinion there are a couple of problems with this solution. In order to see them first we need to see how SpinWait actually works.

SpinOnce uses a counter to determine if it needs to issue a Yield, on each method call this counter gets incremented. If the counter is under ten (10) then Thread.SpinWait will be issued that multiplies the number 4 by 2 to the power of the counter number, so the maximum spin iterations will be 4096 which is allot. If the counter will be grater then ten (10) then a number of context switching methods will be invoked depending on the counter value. Yield will be invoked every time except fifth (Thread.Sleep(0)) and 20th Thread.Sleep(1). This means that after ten (10) iterations SpinWait will issue a light context switch that will issue a switch to another thread on the same processor (!). Then it will try to issue a switch to a thread with the same or higher priority, and finally a switch to thread will be issued with any given priority.

Lock free Data Structures to be performant need to be wait free or limit the number of CAS failures, this requires building the structure in such a way that should we miss the CAS instruction and leave the underlying data structure in a inconsistent or wrong state, some other thread will set it right again. In the context of our example this is not the case as we only have a single and very simple CAS instruction present, that may have a potentially high CAS failures. So to deal with that we might just let the thread spin as it is in our best intentions to let the thread finish the loop as fast as possible, or we could issue a Yield to let another thread waiting on its time slice to continue. Yielding should have a positive effect in high CAS failures as this means that threads have a high overlap ratio and therefor step on each others boots. Issuing a Yield should decrease the overlapping and in result decrease the CAS failure rate.

SpinWait

So what's wrong with SpinWait SpinOnce in this context? The problem is that up to ten (10) failed CAS we issue an Thread.SpinWait that will get expensive fast. Another thing is that we are spinning in the loop right now so there is very little value in spinning again for a increasing number of iterations. The only possible benefit from that is that we might set the processor in the active mode (provided that we aren't in that mode already due to the high load) and thus we will increase the performance but still this will not give us to much benefits (it might if the number of threads isn't to high) as we are in a high contention loop (lots of spinning threads). Another possible benefit is that each thread that failed CAS spins longer than it's previous pair thus racing threads have a chance to align properly and finish the operation, but in reality the penalty of waiting is to high and still even without spin wait the threads should align. Doing performance tests the code without spin waits on average runned faster compared to the original code, the SpinWait solution was on par with commented out solution in a couple of tests but was generally worse.

Proposed Solution

A better solution then using a SpingWait structure would be to have a failed CAS counter that would count failed CAS operations and upon reaching a certain threshold it would issue a Thread.Yield every time to give other threads a chance in finishing their loops for reference let's change the Push() method.

Conclusion

So does this mean that MSDN example code is now ready for production use? Actually no it just means that SpinWait was presented in wrong context and better solution existed and this article was an attempt to explain what's wrong with it to prevent developers from using it in such context.

1 comment:

About Me

I'm a software consultant working day to day on financial systems. I specialize in high frequency concurrent systems that incorporate fragmentation free analysis and software design.
For speaking engagements or other opportunities contact me at: bartoszadamczewski(AT)gmail.com
http://about.me/badamczewski