I need a thread safe queue that yields data if it's not empty, and waits for a data to arrive. With a timeout. I have it like this
void ThreadsafeQueue::enqueue(data_t& data)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(data);
m_condvar.notify_one();
}
boost::optional<data_t> ThreadsafeQueue::dequeue()
{
std::unique_lock<std::mutex> lock(m_mutex);
const std::chrono::seconds DEFAULT_DELAY(10);
if ((!m_queue.empty()) || m_condvar.wait_for(lock, DEFAULT_DELAY) == std::cv_status::no_timeout)
{
const auto data = m_queue.front();
m_queue.pop();
return data;
}
return boost::none;
}
But, for some reason sometimes it sometimes enters the if statement with no_timeout when actually it wasn't notified. And tries to use front() on an empty queue.
Am I doing it wrong?