How To Use Condition Variable

99封情书 提交于 2019-12-17 22:52:21

问题


The Linux Programming Interface book has a piece of code (producer/consumer) to show how condition variable works:

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static int avail = 0;

while (TRUE) {
    s = pthread_mutex_lock(&mtx);

    while (avail == 0) {   /* Wait for something to consume */
       s = pthread_cond_wait(&cond, &mtx);
    }

    while (avail > 0) {   /* Consume all available units */ 
        avail--;
    }

    s = pthread_mutex_unlock(&mtx);
}

Why we use pthread_mutex_lock in while? why we don't use it in an if?


回答1:


Because pthread_cond_signal() is allowed to wake up more than one thread waiting on the condition variable. Therefore you must double-check the condition once you wake up, because some other thread might have woken up and changed it ahead of you.

If you know you have just one thread waiting, and you are sure nobody in the future will ever modify code elsewhere in the program to add another thread waiting, then you can use if. But you never know that for sure, so always use while.

[update]

As ninjalj points out in a comment, my answer is incomplete for failing to mention "spurious wakeups". For example, the POSIX standard makes it clear that if the waiting thread receives a signal (e.g. via kill()), pthread_cond_wait() can return 0 even if no other thread signaled the condition variable. The standard is ambiguous (in my view) as to whether the waiting thread can be woken up for no reason at all... But the bottom line is: Always use while, not if.



来源:https://stackoverflow.com/questions/6206350/how-to-use-condition-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!