Using the mutex lock
Mutexes are also called sleepable or blocking mutual exclusion (mutex) locks. As you have learned, they are used in process context if the critical section can sleep (block). They must not be used within any kind of atomic or interrupt context (top halves, bottom halves such as tasklets or softirqs, and so on), kernel timers, or in process context where blocking is not allowed.
Initializing the mutex lock
Prior to usage, every lock must be initialized to the “unlocked” state. A mutex lock “object” is represented in the kernel as a struct mutex
data structure. Consider the following code:
#include <linux/mutex.h>
struct mutex mymtx;
To use this mutex lock, it must be explicitly initialized to the unlocked state. Initialization can be performed statically (declare and initialize the object) with the DEFINE_MUTEX()
macro, or dynamically via the mutex_init()
function (this is actually a macro wrapper over the __mutex_init...