C ++ 11无法转换std :: condition_variable :: wait from' void'到了布尔'

时间:2015-03-07 12:18:16

标签: c++ multithreading c++11

我正在尝试“C ++编程语言”中的例子。第4版,特别是对condition_variable如何使用的描述。代码段如下:

class Message { // object to be communicated
    // ...
};
queue<Message> mqueue;    // the queue of messages
condition_variable mcond; // the variable communicating events
mutex mmutex;             // the locking mechanism


void consumer()
{
    while(true) {
        unique_lock<mutex> lck{mmutex};           // acquire mmutex
        while (mcond.wait(lck)) /* do nothing */; // release lck and wait;
                                                  // re-acquire lck upon wakeup
        auto m = mqueue.front();                  // get the message
        mqueue.pop();
        lck.unlock();                             // release lck
        // ... process m ...
    }
}

但是,包含mcond.wait(lck)的行的编译失败:

error: could not convert ‘cond.std::condition_variable::wait((* & lck))’ from ‘void’ to ‘bool’

documentation for waitvoid返回类型列出它。这是书中的错误(至少我在勘误表中找不到它)?自该书出版以来(约两年前)该标准是否已更新?如果是这样,在这种情况下我应该如何正确使用wait

我使用的是Lubuntu 14.04 64位,我的gcc版本是4.9.2,我在NetBeans中编译它:

g++ -m64 -pthread -Wextra -c -g -Wall -std=c++11 -MMD -MP -MF "build/Debug/GNU-Linux-x86/main.o.d" -o build/Debug/GNU-Linux-x86/main.o main.cpp

编辑:我刚刚意识到这已经在errata for the previous editions of the book中被发现(在发布此问题之前我忽略了检查,仅查阅第4版)。我仍然希望它对任何碰到它的人都有用。

2 个答案:

答案 0 :(得分:3)

如果您等待超时(相对使用wait_for()或绝对使用wait_until()),则返回类型将为bool。否则,它看起来像书中的一个简单错误。

答案 1 :(得分:1)

你在条件下删除了:

  

mcond.wait(锁);

Errata for 2nd and 3rd printings of The C++ Programming Language