Initialise a mutex statically with PTHREAD_MUTEX_INITIALIZER
Initialise a global pthread mutex at load time with PTHREAD_MUTEX_INITIALIZER in glibc 2.39, with no init call and no destroy for a static mutex.
A mutex that lives for the whole program does not need pthread_mutex_init. Assigning PTHREAD_MUTEX_INITIALIZER at the definition produces a default mutex before main runs, so there is no window where a thread uses an uninitialised lock. That is the standard idiom for file-scope state, shown here with glibc 2.39 and GCC 13 using -pthread.
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int count;
static void *worker(void *arg)
{
(void)arg;
for (int i = 0; i < 1000; i++) {
pthread_mutex_lock(&lock);
count++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void)
{
pthread_t t[4];
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
printf("count=%d\n", count);
return 0;
}count=4000The initialiser only works on a static or otherwise statically allocated object. A mutex inside a malloc'd struct needs pthread_mutex_init and, when you free it, pthread_mutex_destroy; copying a mutex or using a copy is undefined behaviour. The static form takes the default attributes, so it is not recursive and not error-checking. Use PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP on glibc if you need a recursive one. See pthread_mutex_init(3p).