xiao su
xiao su

Reputation: 167

if pthread_cond_wait can loss signal when pthread_cond_signal signal before it

================thread1

pthread_mutex_lock(&mutex);
do 
{
    fun();//this fun will cost a long time, maybe 1-2 second
    gettimeofday(&now, NULL);
    outtime.tv_sec = now.tv_sec + 5;
    outtime.tv_nsec = now.tv_usec * 1000;
    int ret = pthread_cond_timedwait(&cond, &mutex, &outtime);    
} while((!predicate && ret != ETIMEDOUT)
pthread_mutex_unlock(&mutex);

==========================thread2

pthread_mutex_lock(&mutex);
predicate = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);

if thread2 send a signal during thread1's fun(), there is no pthread_cond_timedwait, when fun() call return, the phread_cond_timedwait in thread1 still can get the signal that thread2 has sent before or not? can we call a time-consuming fun before pthread_cond_timedwait in while()??

Upvotes: 0

Views: 179

Answers (1)

Pete Becker
Pete Becker

Reputation: 76498

If pthread_cond_signal is called when no thread is waiting for a signal it has no effect. The signal is not stored for future use.

If predicate is true, the code in the loop should not wait for the condition variable.

Upvotes: 1

Related Questions