On Thu, 9 Dec 2004 kernel-stuff@xxxxxxxxxxx wrote:I didn't take pre-emption into account. Although I would not have readily thought about the need to disable Pre-emption even if I had considered it :-) So thanks for the correction!
Spinlocks are used in situations where multiple threads contend for a lock and they can possibly run on more than one CPU. Example - Thread A is executing on CPU-A, Thread B in executing on CPU-B. They contend for a lock L1. A acquires the lock first. B tries (on CPU-B) to acquire the lock L1 and finds it is not free - so it just spins (executes a no-op kind of loop ) until Thread A relinquishes the lock L1. Spinlocks are used in cases where the operation performed under a lock is short one - takes very less time. In these type of cases, spinning is less costlier than sleeping which involves scheduler overhead. So if we take out CPU-B from the above equation - there is no chance for Thread B to execute to contend for lock L1 without thread A going to sleep. That's why spinlocks are useless on 1 CPU machine.
Your last sentence is incorrect. Spinlocks on 1 CPU machines still need to disable preemption (assuming preemption is compiled in obviously, if not then indeed you are right). Otherwise preemption could take place in the middle of a data manipulation and you would still have the same race as you described with two cpus working concurrently. Except that with preemption it is only logical concurrence not actual physical concurrence.