What are Synchronization techniques or Explain spinlock and mutex ?

 Spin lock and mutex (short for mutual exclusion) are the two basic synchronization mechanisms used to protect critical sections (A code area that accesses shared resources is called a critical section) in the kernel to prevent the race conditions.

A spin lock make sure that only one thread enters into critical section at a time. Any other
thread that desires to enter the critical section has to remain spinning at the door until the
first thread exits (here the term "thread" to refer to a thread of execution rather
than a kernel thread).

The spinlocks usage is as follows (this is basic way):
    #include <linux/spinlock.h>
    spinlock_t mylock = SPIN_LOCK_UNLOCKED; /* Initialize */
    /* Acquire the spinlock. This is inexpensive if there
     * is no one inside the critical section. In the face of
     * contention, spinlock() has to busy-wait.
     */
    spin_lock(&mylock);
    /* ... Critical Section code ... */
    spin_unlock(&mylock); /* Release the lock */
 

 Spinlocks that put threads into a spin state if they attempt to enter a busy critical section area, but mutexes put threads to sleep until it's their turn to come to acquire the critical section area. Because spnilcok has bad thing, that consumes processor cycles to spin, but mutexes are more suitable than spinlocks to protect critical sections when the estimated wait time is more ( but that critical region is must not be part of interrupt routines). 

For mutex, anything more than two context switches is considered as long period, because a mutex has to switch out the thread to sleep and switch it back in when it's time to wake it up.

Below is mutex usage :

#include <linux/mutex.h>
/* Statically declare a mutex. To dynamically
 create a mutex, use mutex_init() */
static DEFINE_MUTEX(mymutex);
/* Acquire the mutex. This is inexpensive if there
 * is no one inside the critical section. In the face of
 * contention, mutex_lock() puts the calling thread to sleep.
 */
mutex_lock (&mymutex);
/* ... Critical Section code ... */
mutex_unlock (&mymutex); /* Release the mutex */


Previous Post Next Post

Contact Form