Article

Uninitialized Mutexes

Detects when a mutex is used before it’s initialized.

Overview

This check detects anytime pthread_mutex_lock(_:) or pthread_mutex_unlock(_:) is called with a pthread_mutex_t variable that wasn’t initialized. Attempting to use an uninitialized mutex results in an error, and removes any guarantees about ordering that would exist while a mutex is locked.

Use of Uninitialized Mutex in C

In the following example, the pthread_mutex_lock(_:) function is called on an uninitialized pthread_mutex_t variable.

static pthread_mutex_t mutex;
void performWork() {
    pthread_mutex_lock(&mutex); // Error: uninitialized mutex
    // ...
    pthread_mutex_unlock(&mutex);
}

Solution

Use the pthread_once(_:_:) function to ensure that initialization is called before a mutex is used.

static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_mutex_t mutex;
void init() {    
    pthread_mutex_init(&mutex, NULL);
}
void performWork() {
    pthread_once(&once, init); // Correct
    pthread_mutex_lock(&mutex);
    // ...
    pthread_mutex_unlock(&mutex);
}

See Also

Thread Sanitizer Checks

Data Races

Detects unsynchronized access to mutable state across multiple threads.

Swift Access Races

Detects when multiple threads call a mutating method on the same structure, or pass a shared variable as inout without synchronization.

Races on Collections and Other APIs

Detects when a thread accesses a mutable object while another thread writes to that object, causing a data race.

Thread Leaks

Detects when threads aren’t closed after use.