A coworker recently asked for my opinions on a thread safe queue class he is modifying. A shortened version of the waitAndPop method is below:
std::shared_ptr<T> waitAndPop() {
std::unique_lock<std::mutex> lock(mut);
dataCond.wait(lock, [this] { return (!dataQueue.empty() || !queueAlive);});
if (dataQueue.empty() || !queueAlive)
return std::shared_ptr<T>(); // NULL
std::shared_ptr<T> result = dataQueue.front();
dataQueue.pop();
return result;
}
A common dilemma with these sorts of classes is how to handle breaking out of the condition wait on shutdown. In this case, he eventually returns a null pointer. Returning null pointers from modern C++ seems clunky and outdated to me and places a burden on the user. I'd prefer throwing an exception or ignore it altogether, forcing the user to cooperatively shutdown.
My question is what's the best way to handle this situation?