Why do we need a condition check before pthread_cond_wait

后端 未结 2 1589
陌清茗
陌清茗 2020-12-15 06:37

I am trying to learn basics of pthread_cond_wait. In all the usages, I see either

if(cond is false)
   pthread_cond_wait

or



        
2条回答
  •  心在旅途
    2020-12-15 07:08

    You need a while loop because the thread that called pthread_cond_wait might wake up even when the condition you are waiting for isn't reached. This phenomenon is called "spurious wakeup".

    This is not a bug, it is the way the conditional variables are implemented.

    This can also be found in man pages:

    Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

    Update regarding the actual code:

    void* proc_add(void *name) 
    {
        struct vars *my_data = (struct vars*)name;
    
        printf("In thread Addition and my id = %d\n",pthread_self());
    
        while(1) {
    
            pthread_mutex_lock(&mutexattr);
    
            while(!my_data->ipt){  // If no input get in
                pthread_cond_wait(&mutexaddr_add,&mutexattr);  // Wait till signalled
            }
    
            my_data->opt = my_data->a + my_data->b;
            my_data->ipt=1;
            pthread_cond_signal(&mutexaddr_opt);
    
            pthread_mutex_unlock(&mutexattr);
    
            if(my_data->end)
                pthread_exit((void *)0);
            }
        }
    }
    

提交回复
热议问题