Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Friday, August 24, 2007

Spin lock, OS scheduler, and SMP

Is it possible to optimize a spinlock without using a schedular (or some refer to as OS APIs). The answer is not efficiently.

On OS with pre-emptive kernels such as most Windows and Linux kernels, high priority process/thread can preempt low priority task that is spending most of its time busy looping in a spinlock. By moving such a low priority task to sleep state, the kernel is effectively optimizing cpu use. You will notice your UP system is a little slower but it's still quite usable. The reason for the slowdown is that the spinlock thread is simply not very cooperative and does not yield cpu time.

Another factor to consider is SMP. On multi processor machine, such a busy loop process is usually bound to a particular cpu and user can hardly notice any kind of system slowdown for interactive work. This is a very easy experiment to try out.

Is there room for a little bit optimization on SMP system? Check out 'lock xchg'. The memory subsystem will kick in and block such a thread from execution until the bus is locked to synchronize this memory value between multiple CPUs.