cs24-23fa pthread_mutex_init

Introduction to Computing Systems (Fall 2023)


pthread_mutex_destroy, pthread_mutex_init — destroy and initialize a mutex


#include <pthread.h>

int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;



The pthread_mutex_init() function shall initialize the mutex referenced by mutex with attributes specified by attr. If attr is NULL, the default mutex attributes are used; the effect shall be the same as passing the address of a default mutex attributes object. Upon successful initialization, the state of the mutex becomes initialized and unlocked.

Attempting to initialize an already initialized mutex results in undefined behavior.


The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized.

It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex, or a mutex that another thread is attempting to lock, or a mutex that is being used in a pthread_cond_wait() call by another thread, results in undefined behavior.


#include <pthread.h>
pthread_mutex_t mutex;

int main(int argc, char *argv[]) {
    pthread_mutex_init(&mutex, NULL);
    return 0;

Return Value

If successful, the pthread_mutex_destroy() and pthread_mutex_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

See Also

pthread_mutex_lock(), pthread_cond_wait()