2.5. mutex
— Mutual exclusion¶
A mutex is a synchronization primitive used to protect a shared resource.
2.5.1. Example usage¶
This is a small example of protecting a shared resource with a mutex.
struct mutex_t mutex;
int resource = 0;
/* Initialize the mutex. */
mutex_init(&mutex);
/* Increment the shared resource by one. */
mutex_lock(&mutex);
resource++;
mutex_unlock(&mutex);
Source code: src/sync/mutex.h, src/sync/mutex.c
Test code: tst/sync/mutex/main.c
Test coverage: src/sync/mutex.c
Functions
-
int
mutex_module_init
(void)¶ Initialize the mutex module. This function must be called before calling any other function in this module.
The module will only be initialized once even if this function is called multiple times.
- Return
- zero(0) or negative error code
-
int
mutex_init
(struct mutex_t *self_p)¶ Initialize given mutex object.
- Return
- zero(0) or negative error code.
- Parameters
self_p
: Mutex to initialize.
-
int
mutex_lock
(struct mutex_t *self_p)¶ Lock given mutex.
- Return
- zero(0) or negative error code.
- Parameters
self_p
: Mutex to lock.
-
int
mutex_unlock
(struct mutex_t *self_p)¶ Unlock given mutex.
- Return
- zero(0) or negative error code.
- Parameters
self_p
: Mutex to unlock.
-
struct
mutex_t
¶