cs24-22fa pthread_mutex_init

Introduction to Computing Systems (Fall 2022)

Name

pthread_mutex_destroy, pthread_mutex_init — destroy and initialize a mutex

Synopsis

#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;

Description

Initialization

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.

Destruction

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.

Example

#include <pthread.h>
pthread_mutex_t mutex;

int main(int argc, char *argv[]) {
    pthread_mutex_init(&mutex, NULL);
    pthread_mutex_destroy(&mutex);
    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()