Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex not initialized

Tags:

linux

Does anyone know if when creating a mutex, it's a must to initialize it or can i lock it directly without calling pthread_mutex_init?

I have done a sample application that simulates a deadlock just to make sure the mutex work and have declared 2 mutexes(to create the deadlock) in the following way:

static pthread_mutex_t fastmutex1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t fastmutex2 = PTHREAD_MUTEX_INITIALIZER; 

The deadlock perfectly works which makes sense since it's initialized with some defaults. On the other hand when doing the exact same thing with this:

static pthread_mutex_t fastmutex1;
static pthread_mutex_t fastmutex2;

I expected that not to work but the deadlock appeared in the exact same way as the previous example.

By the way I am running that on Linux kernel 2.6.18

Thx for help.

like image 604
isaac.hazan Avatar asked May 23 '26 23:05

isaac.hazan


2 Answers

According to this documentation (And everything else I've ever read or personally done with pthreads):

Mutex variables must be declared with type pthread_mutex_t, and must be initialized before they can be used.

I suspect anything else is going to trigger undefined behavior.

like image 158
Brian Roach Avatar answered May 26 '26 12:05

Brian Roach


On my Debian/Sid/AMD64 system, /usr/include/pthread.h contains

 # define PTHREAD_MUTEX_INITIALIZER \
   { { 0, 0, 0, 0, 0, 0, { 0, 0 } } }

This means that (on my system) a pthread_mutex_t is valuably initialized to all zeros. And a static variable is initialized (in C) to all zeros, which happens to be the same at runtime (and explains the behavior you've got).

However, there is no guarantee that PTHREAD_MUTEX_INITIALIZER will stay the same, or that is is all zeros on other systems. So you better explicitly initialize a static pthread_mutex_t variable with it.

like image 36
Basile Starynkevitch Avatar answered May 26 '26 12:05

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!