[Ilugc] what is spinlock

  • From: rsubr@xxxxxxxxxxxxxxxxxxxxxxxx (Raja Subramanian)
  • Date: Thu, 3 Jun 2004 23:31:53 +1000

Hi,

carti wrote:

Can anyone who knows well explain with example
of what is spinlock?

...

Something like the following it says.

spinlock like a semaphore but has no process list. And when
a process finds a lock closed by another process, its "spins"
around repeatedly, executing a tight instruction loop until the lock
becomes open.

I dont especially understand what is spinning and executing a
right instruction loop.

Spinlock (aka busy lock) is when a thread repeatedly tests for a
condition.  Eg.  Look at the following C code -

 1. while (lock == 1) continue;     /* tight loop */
 2. lock = 1;
 3. /* critical section goes here */
 4. lock = 0;

When executing this code the thread waits for some other thread to
set lock to zero.  When lock is zero, the thread enters the critical
section.

A tight loop is a loop with a very small body.  Spinning is the slang
for repeatedly executing a tight loop that effectively does nothing
(like line 1 above).

Note: a race condition exists between lines 1,2.  There exists the
possibility that more than one thread can enter the critical section at
the same time.  This is because, the "test" to check "lock == 0" and the
"set" "lock = 1" operations are not atomic.  Atomic test-and-set support
from the hardware helps in preventing this.  See the 'membar' (memory
barrier) instruction on Alpha architectures for how atomic test-and-set
is implemented in hardware.

Spinlocks have the following features -
  1. eats CPU - you are constantly checking lock status
  2. you cannot hold this lock for long without degrading performance 
     the rule of thumb goes that spinlocks are fine upto 150 iterations
     of your (while) loop.
  3. on a lot of CPU architectures (esp ones that implement atomic
     test-and-set instructions), spinlocks are cheap to create.
  4. can be implemented without kernel support


Semaphores are different in that while waiting to obtain a lock, a
thread is 'put to sleep' and does not consume any CPU cycles.  The
thread is woken up (by the kernel or the threading library) when the
lock becomes available.  Creating/using semaphores is expensive because
the kernel/threading library has to setup/maintain some internal data
structures, so its best to use them in cases where you have to wait a
long time to obtain a lock.

HTH,

- Raja


Other related posts: