Introduction to spinlocks

Spinlocks are one of the ways of achieving mutual exclusion that is, preventing multiple processes from entering the critical section simultaneously.
A spinlock has only two possible states, LOCKED and UNLOCKED.

A critical section can be surrounded by spinlock as shown below.

Critical section

Let us say two processes, A and B, want to execute the critical section and both reach the step of locking the spinlock at the same time.

Let us say process A is able to get a lock on the spinlock before process B. The process A can enter the critical section.
The process B will try to lock the spinlock but will fail as process A would have already locked it. As a result the process B will go into into an infinite spin on the lock, that is, it will keep checking for the availability of the lock repeatedly until the spinlock gets unlocked by process A. Because of this behavior of continuously spinning on the lock until it becomes available these are called as spinlocks

After finishing the execution of critical section process A will unlock the spinlock at which time the process B will be able to get the lock and enter the critical section.

Thus if a critical section is surrounded by a spinlock only one process can enter the critical section at any given time. Any number of processes can be spinning on the lock but only of the processes will be allowed to enter the critical section once the lock becomes available.

The following animation shows the working of a spinlock as explained above.

Spinlock animation

 photo spin_lock1.gif

Tags: ,
Copyright 2017. All rights reserved.

Posted June 6, 2013 by Tux Think in category "Linux