Nobilis Nobilis - 13 days ago 7
C++ Question

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 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:

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

I'm using Lubuntu 14.04 64bit, my gcc version is 4.9.2, I'm compiling it in NetBeans with:

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


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). Still I hope it is of use to anyone who comes across it.

Answer

If you wait with a timeout (relative using wait_for() or absolute using wait_until()), then the return type will be bool. Otherwise, it looks like a simple error in the book.

Comments