Use pthread_mutex_init(3C) to initialize the mutex pointed at by mp to its default value or to specify mutex attributes that have already been set with pthread_mutexattr_init() . The default value for mattr is NULL .
int pthread_mutex_init(pthread_mutex_t *restrict mp, const pthread_mutexattr_t *restrict mattr);
#include <pthread.h> pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t mattr; int ret; /* initialize a mutex to its default value */ ret = pthread_mutex_init(&mp, NULL); /* initialize a mutex */ ret = pthread_mutex_init(&mp, &mattr);
When the mutex is initialized, the mutex is in an unlocked state. The mutex can be in memory that is shared between processes or in memory private to a process.
For a mutex that is being initialized with the PTHREAD_MUTEX_ROBUST_NP attribute, the mutex memory must be cleared to zero before initialization.
The effect of mattr set to NULL is the same as passing the address of a default mutex attribute object, but without the memory overhead.
Use the macro PTHREAD_MUTEX_INITIALIZER to initialize statically defined mutexes to their default attributes.
Do not reinitialize or destroy a mutex lock while other threads are using the mutex. Program failure results if either action is not done correctly. If a mutex is reinitialized or destroyed, the application must be sure the mutex is not currently in use.
pthread_mutex_init() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.
The implementation has detected an attempt to reinitialize the object referenced by mp, a previously initialized but not yet destroyed mutex.
The mattr attribute value is invalid. The mutex has not been modified.
The address for the mutex pointed at by mp is invalid.