According to the documentation a mutex can be initialized in two ways:
Using the init function:
pthread_mutex_t theMutex;
pthread_mutex_init(&theMutex, NULL);
Using an initializer macro:
pthread_mutex_t result = PTHREAD_MUTEX_INITIALIZER;
About the latter the documentation says:
In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.
Does this mean that it may only be used for static variables and not for local variables?
C++ Specific
I wanted to use the following “factory function”:
static pthread_mutex_t GetFastNativeMutex()
{
static pthread_mutex_t result = PTHREAD_MUTEX_INITIALIZER;
return result;
}
Because it would allow me to initialize mutexes in a C++ initializer list as follows:
MyClass() : myMutex(GetFastNativeMutex()) {}
Is this valid? (Btw in practice it works. Valgrind also doesn’t complain.)
Update
If I understood the documentation correctly then this should be ok:
#include <pthread.h>
static pthread_mutex_t m0 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
However, when looking at the preprocessor output (using gcc -E main.cpp) I see the following:
static pthread_mutex_t m0 = {0x32AAABA7, {0}};
static pthread_mutex_t m1 = {0x32AAABA7, {0}};
static pthread_mutex_t m2 = {0x32AAABA7, {0}};
It turns out that three times the same mutex was created. What am I doing wrong here?
Re “It turns out that three times the same mutex was created. What am I doing wrong here?”
You are doing nothing wrong here. The same mutex was not created three times. It looks like you are interpreting that 0x32AAABA7 as an address. It isn’t. It is essentially an enum value, but with a Hamming code protection to (a) make it safe and (b) make it obscure. You have three distinct mutexes here.