如何使用条件变量 [英] How To Use Condition Variable

查看:121
本文介绍了如何使用条件变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Linux的编程接口书中有一张code(生产者/消费者)的显示条件变量是如何工作的:

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);
}

为什么我们使用的pthread_mutex_lock ,而?为什么我们不使用它的如果

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

推荐答案

由于<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_signal.html\">pthread_cond_signal()允许唤醒多个线程等待条件变量。因此,你必须仔细检查病情,一旦你醒来,因为一些其他线程可能会被唤醒,改变了它在你前面。

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.

如果你知道你只有一个线程在等待,而你在未来肯定没有人会修改code其他地方的程序中加入另外一个线程等待,那么你可以使用如果。但你永远不知道,可以肯定,因此请务必使用,而

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.

[更新]

作为ninjalj在评论中指出的那样,我的答案是不完全未能提虚假唤醒。例如,POSIX标准明确指出,如果等待线程接收信号(例如通过kill()),调用pthread_cond_wait()可以返回0,即使没有其他线程信号的条件变量。该标准是模糊的(在我看来),是否等待的线程可以在所有被唤醒无故...但底线是:总是的使用,而,而不是如果

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.

这篇关于如何使用条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆