Search notes:

Kernel lock: mutex

Mutexes enforce serialization on shared memory systems. Unlike spinlocks, a process trying to acquire a mutex will suspend itself if it fails to acquire it. The process is then woken up when the mutex is available. This has the advantage that the CPU is free to persue another task.
A mutex is represented by struct mutex, defined in include/linux/mutex.h.

Semantics

A lock can be held/owner by at most one owner at a time.
Only this owner can release the lock when held. When a tasks holds a mutex, it must not exit.
A mutex object must be initialized through an API, not via memset or copying. The memory containing the mutex may not be freed.
Mutexes may not be used in hardware or software interrupts such as tasklets and timers.

Code snippets

Statically define the mutex:
DEFINE_MUTEX(name);
Dynamically initialize the mutex:
mutex_init(mutex);
Acquire the mutex, uninterruptible
void mutex_lock(struct mutex *lock);
void mutex_lock_nested(struct mutex *lock, unsigned int subclass);
int  mutex_trylock(struct mutex *lock);
Acquire the mutex, interruptible:
int mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass);
int mutex_lock_interruptible(struct mutex *lock);
Acquire the mutex, interruptible, if dec to 0:
int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock);
Unlock the mutex:
void mutex_unlock(struct mutex *lock);
Test if the mutex is taken:
int mutex_is_locked(struct mutex *lock);

CONFIG_DEBUG_MUTEXES

When CONFIG_DEBUG_MUTEXES is enabled, violation of the semantics are enforced and reported.

TODO

futex: Fast user space mutex.

See also

Kernel locks, spninlocks, include/linux/mutex.h, kernel/locking/mutex.c, Documentation/locking/mutex-design.txt, Documentation/DocBook/genericirq.tmpl

Index