I've never had the chance to play with the pthreads library before, but I am reviewing some code involving pthread mutexes. I checked the documentation for pthread_mutex_lock
and pthread_mutex_init
, and my understanding from reading the man pages for both these functions is that I must call pthread_mutex_init
before I call pthread_mutex_lock
.
However, I asked a couple colleagues, and they think it is okay to call pthread_mutex_lock
before calling pthread_mutex_init
. The code I'm reviewing also calls pthread_mutex_lock
without even calling pthread_mutex_init
.
Basically, is it safe and smart to call pthread_mutex_lock
before ever calling pthread_mutex_init
(if pthread_mutex_init
even gets called)?
EDIT: I also see some examples where pthread_mutex_lock
is called when pthread_mutex_init
is not used, such as this example
EDIT #2: Here is specifically the code I'm reviewing. Please note that the configure function acquires and attaches to some shared memory that does not get initialized. The Java code later on will call lock()
, with no other native functions called in-between. Link to code
Mutexes are variables containing state (information) that functions need to do their job. If no information was needed, the routine wouldn't need a variable. Likewise, the routine can't possibly function properly if you feed random garbage to it.
Most platforms do accept a mutex object filled with zero bytes. This is usually what
pthread_mutex_init
andPTHREAD_MUTEX_INITIALIZER
create. As it happens, the C language also guarantees that uninitialized global variables are zeroed out when the program starts. So, it may appear that you don't need to initializepthread_mutex_t
objects, but this is not the case. Things that live on the stack or the heap, in particular, often won't be zeroed.Calling
pthread_mutex_init
afterpthread_lock
is certain to have undesired consequences. It will overwrite the variable. Potential results:The POSIX standard says:
So you do need to initialise the mutex. This can be done either by a call to
pthread_mutex_init()
; or, if the mutex has static storage duration, by using the static initializerPTHREAD_MUTEX_INITIALIZER
. Eg:here is the text from the link I posted in a comment: