question about mutex initialization

Hi,

For mutex, I normally initialize it before using it as

pthread_mutex_init(&mutex, NULL);

However, I found in one of my applications, I declare an array of mutex in header as

MyClass.h
static pthread_mutex_t a[10];

MyClass.cpp
then, it is defined in the cpp file as
pthread_mutex_t MyClass::a[10];

I totally forgot to do init. The applications seems working. So my question is
if I define a mutex as that, will that be initialized in definition?

Thanks

Chris
No.

Try this:

 
pthread_mutex_t MyClass::a[10] = { PTHREAD_MUTEX_INITIALIZER };

it is a mystery to me why the codes worked before. anyway, is the function above equal to

for(int i = 0; i < 10; i ++)
{
pthread_mutex_init(&a[i], NULL);
}

I never use PTHREAD_MUTEX_INITIALIZER and do not know it can used this way for array. HOwever, my understanding is taht it can ONLY be used for static mutex and be initialized the first time the mutex get called, right?

Thanks
pthread_mutex_t, at least in my implementation (POSIX defines it as an opaque type), is a struct containing several member variables that happen to want to be initialized to 0 in order to work properly. Your static array probably happens to be allocated in memory that is already initialized to zero, so it happens to work.

Nonetheless, to be safe, you should initialize the mutexes.

I just verified that my above code will not work. You need to do the for() loop as you wrote above instead.
Topic archived. No new replies allowed.