Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PTHREAD_COND_INITIALIZER may be used to initialize a condition variable only when it is declared?

Since the PTHREAD_COND_INITIALIZER is actually a structure initializer, it may be used to initialize a condition variable only when it is declared.

From: Multi-Threaded Programming With POSIX Threads

Question: Couldn't understand the above quote.
It is just a macro, why can't I use it to initialize the condition variable on run time?
What has its being a structure initializer to do with anything?

like image 644
Aquarius_Girl Avatar asked Feb 27 '12 10:02

Aquarius_Girl


1 Answers

Because it is a structure initializer, you cannot use it to init the structure in a statement apart from its declaration.

It is defined on my system like so:

#define PTHREAD_COND_INITIALIZER {_PTHREAD_COND_SIG_init, {0}}

Expanded and used, we see:

pthread_cond_t p = PTHREAD_COND_INITIALIZER; // << ok!
p = PTHREAD_COND_INITIALIZER; // << compiler error =\

That is,

p = PTHREAD_COND_INITIALIZER;

expands to:

p = {_PTHREAD_COND_SIG_init, {0}};
like image 78
justin Avatar answered Oct 22 '22 01:10

justin