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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With