Skip to content

mutex_lock() / mutex_unlock()

Purpose

Protects shared state in process context where sleeping is allowed.

#include <linux/mutex.h>

Prototype

void mutex_lock(struct mutex *lock);
void mutex_unlock(struct mutex *lock);

Parameters

  • lock: pointer to an initialized struct mutex.

Return Value

  • mutex_lock() returns no value and may sleep.
  • mutex_unlock() releases the mutex.

Minimal Example

mutex_lock(&dev->lock);
/* update shared state */
mutex_unlock(&dev->lock);

Common Pitfalls

  • Do not use mutexes in hard IRQ context.
  • Avoid holding mutexes while copying large data to/from user space.
  • Use clear ownership rules to prevent deadlocks.