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.
On my Debian/Sid/AMD64 system,
/usr/include/pthread.hcontainsThis means that (on my system) a
pthread_mutex_tis 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_INITIALIZERwill stay the same, or that is is all zeros on other systems. So you better explicitly initialize a staticpthread_mutex_tvariable with it.