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

问题描述

我是多线程的新手.使用条件变量在C ++ 11中编写多线程代码时,我使用以下结构

I am new to multi threading. While writing multi threaded code in C++11 using condition variable , I use the following construct

while(predicate) {
    cond_var.wait(&lock);
}

但是,我一直在阅读Deitel关于操作系统的第三版(第6章),其中使用了以下结构

However, I have been reading Deitel's third edition book on operating systems(chp 6) where the following construct is being used

if(predicate) {
    cond_var.wait(&lock);
}

那么,有什么区别?为什么书不使用一会儿?伪造不是问题吗?

So, what's the difference? Why isn't the book using while? Isn't spurious call an issue?

推荐答案

虚假唤醒始终是一个潜在问题.例如,在此处查看答案:虚假唤醒是否真的发生了?.也许Deitel的代码是更大循环的一部分,可以帮助他们处理虚假唤醒?也许只是错字.

Spurious wakeup is always a potential issue. For example, look at the answers here: Do spurious wakeups actually happen?. Perhaps Deitel's code is part of a larger loop that can help them deal with the spurious wakeup? Or maybe it's just a typo.

在任何情况下,从来没有(好的)理由不使用您的构造,实际上, wait 函数有一个变体可以满足您的需要( http://en.cppreference.com/w/cpp/thread/condition_variable/wait ).

In any case, there's never a (good) reason not to use your construct, and in fact the wait function has a variant that does it for you (http://en.cppreference.com/w/cpp/thread/condition_variable/wait).

template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );

等效于:

while (!pred()) {
     wait(lock);
}

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

08-23 17:25