Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

c++ - condition variable - why calling pthread_cond_signal() before calling pthread_cond_wait() is a logical error?

It's written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error.

my question is why it is a logical error?

In my program i need to use these signals, however i cannot guarantee that there will be a thread that will be in _cond_wait state. I tried to test it and nothing happens. Is this can cause unexpected behavior or worse?

thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer of blaze comes closest, but is not totally clear:
conditional variables should only be used to signal a change in a condition.

Thread 1 checks a condition. If the condition doesn't meet, he waits on the condition variable until the condition meets. Because the condition is checked first, he shouldn't care whether the condition variable was signaled:

pthread_mutex_lock(&mutex); 
while (!condition)
    pthread_cond_wait(&cond, &mutex); 
pthread_mutex_unlock(&mutex);

Thread 2 changes the condition and signals the change via the condition variable. He doesn't care whether threads are waiting or not:

pthread_mutex_lock(&mutex); 
changeCondition(); 
pthread_mutex_unlock(&mutex); 
pthread_cond_signal(&cond)

The bottom line is: the communication is done via some condition. A condition variable only wakes up waiting threads so they can check the condition.

Examples for conditions:

  • Queue is not empty, so an entry can be taken from the queue
  • A boolean flag is set, so the thread wait s until the other thread signal it's okay to continue
  • some bits in a bitset are set, so the waiting thread can handle the corresponding events

see also pthread example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...