andersch.dev

<2025-04-14 Mon>

Mutex

In multithreading, a mutex (mutual exclusion) is a synchronization primitive that prevents multiple threads from simultaneously accessing shared resources.

It acts as a lock that only one thread can hold at a time - when a thread acquires the mutex, others attempting to access the same resource must wait until the mutex is released

The use of mutexes can prevent race conditions, but may also introduce performance bottlenecks and deadlocks.

Basic Mutex API

int mutex_init(mutex_t *mutex);
int mutex_lock(mutex_t *mutex);    // blocking, waits until mutex available
int mutex_trylock(mutex_t *mutex); // non-blocking, returns with success or failure
int mutex_unlock(mutex_t *mutex);  // unlock a mutex
int mutex_destroy(mutex_t *mutex);