Use pthread_mutex_init(3THR) to initialize the mutex pointed at by mp to its default value (mattr is NULL), or to specify mutex attributes that have already been set with pthread_mutexattr_init(). (For Solaris threads, see "mutex_init(3THR)".)
Prototype: int pthread_mutex_init(pthread_mutex_t *mp, const pthread_mutexattr_t *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, it is in an unlocked state. The mutex can be in memory shared between processes or in memory private to a process.
The mutex memory must be cleared to zero before initialization.
The effect of mattr being NULL is the same as passing the address of a default mutex attribute object, but without the memory overhead.
Statically defined mutexes can be initialized directly to have default attributes with the macro PTHREAD_MUTEX_INITIALIZER.
A mutex lock must not be reinitialized or destroyed while other threads might be using it. Program failure will result 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 returned 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).