简体   繁体   English

C ++ 11无法将std :: condition_variable :: wait从'void'转换为'bool'

[英]C++11 could not convert std::condition_variable::wait from 'void' to 'bool'

I'm trying out the examples in 'The C++ Programming Language' 4th edition and in particular, there's a description of how a condition_variable is used. 我正在尝试“The C ++ Programming Language”第4版中的示例,特别是有一个如何使用condition_variable的描述。 The code snippet is as follows: 代码段如下:

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 ...
    }
}

However compilation fails on the line containing mcond.wait(lck) with: 但是,包含mcond.wait(lck)的行上的编译失败:

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

The documentation for wait lists it with a void return type. wait文档列出了void返回类型。 Is this an error in the book (at least I couldn't find it in the errata)? 这是书中的错误(至少我在勘误表中找不到它)? Has the standard been updated since the book came out (about two years ago)? 自该书出版以来(约两年前)该标准是否已更新? If so, how should I use wait correctly in this case? 如果是这样,在这种情况下我应该如何正确使用wait

I'm using Lubuntu 14.04 64bit, my gcc version is 4.9.2, I'm compiling it in NetBeans with: 我正在使用Lubuntu 14.04 64bit,我的gcc版本是4.9.2,我在NetBeans中编译它:

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

EDIT: I've just realised that this has been already spotted in the errata for the previous editions of the book (which I neglected to check prior to posting this question, consulting only the 4th edition one). 编辑:我刚刚意识到这已经出现在本书以前版本勘误表中 (我在发布此问题之前忽略了检查,仅查阅第4版)。 Still I hope it is of use to anyone who comes across it. 我仍然希望它对任何碰到它的人都有用。

If you wait with a timeout (relative using wait_for() or absolute using wait_until() ), then the return type will be bool . 如果等待超时(相对使用wait_for()或绝对使用wait_until() ),则返回类型将是bool Otherwise, it looks like a simple error in the book. 否则,它看起来像书中的一个简单错误。

You shoud delete while condition: 条件时你应该​​删除:

mcond.wait(lock); mcond.wait(锁);

Errata for 2nd and 3rd printings of The C++ Programming Language 用于C ++编程语言第2和第3次印刷的勘误表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM