Chapter 3. Locking in the Linux Kernel
Prev |  | Next

## Chapter 3. Locking in the Linux Kernel

If I could give you one piece of advice: never sleep with anyone crazier than yourself. But if I had to give you advice on locking: keep it simple.

Be reluctant to introduce new locks.

Strangely enough, this last one is the exact reverse of my advice when you have slept with someone crazier than yourself. And you should think about getting a big dog.

## Three Main Types of Kernel Locks: Spinlocks, Mutexes and Semaphores

There are three main types of kernel locks. The fundamental type is the spinlock (`include/asm/spinlock.h`), which is a very simple single-holder lock: if you can't get the spinlock, you keep trying (spinning) until you can. Spinlocks are very small and fast, and can be used anywhere.

The second type is a mutex (`include/linux/mutex.h`): it is like a spinlock, but you may block holding a mutex. If you can't lock a mutex, your task will suspend itself, and be woken up when the mutex is released. This means the CPU can do something else while you are waiting. There are many cases when you simply can't sleep (see Chapter 9, What Functions Are Safe To Call From Interrupts?), and so have to use a spinlock instead.

The third type is a semaphore (`include/asm/semaphore.h`): it can have more than one holder at any time (the number decided at initialization time), although it is most commonly used as a single-holder lock (a mutex). If you can't get a semaphore, your task will be suspended and later on woken up - just like for mutexes.

Neither type of lock is recursive: see the section called “Deadlock: Simple and Advanced”.

Prev |  | Next
Chapter 2. The Problem With Concurrency | Home | Locks and Uniprocessor Kernels