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

11,737

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}};
Share:
11,737
Aquarius_Girl
Author by

Aquarius_Girl

Arts and Crafts.stackexchange.com is in public beta now. Join us!

Updated on August 13, 2022

Comments

  • Aquarius_Girl
    Aquarius_Girl over 1 year

    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?

  • Aquarius_Girl
    Aquarius_Girl about 12 years
    Since you've shown the code, I understand the meaning. Thanks, didn't know the "term" structure initializer. Very helpful.
  • justin
    justin about 12 years
    @AnishaKaul you're welcome. note also that you could reinitialize it using C99 compound literals, provided of course it either failed initialization or has been destroyed, and your compiler supports C99 compound literals (not always C++ friendly). Here's the form: p = (pthread_cond_t)PTHREAD_COND_INITIALIZER; -- which expands to p = (pthread_cond_t){_PTHREAD_COND_SIG_init, {0}};.