condition variable wait unlocks mutex c++ code example
Example: condition variable wait unlocks mutex c++
std::mutex mutex;
std::queue buffer;
std::condition_variable buffer_cond;
void data_preparation_thread()
{
while(has_data_to_prepare()) //-- (1)
{
buffer_data data = prepare_data();
std::lock_quard lock(mutex); //-- (2)
buffer.push(data);
buffer_cond.notify_one(); //-- (3)
}
}
void data_processing_thread()
{
while(true)
{
std::unique_lock lock(mutex); //-- (4)
buffer_cond.wait(lock, []{return ! buffer.empty()}) //-- (5)
buffer_data data = buffer.front();
buffer.pop();
lock.unlock(); //-- (6)
process(data);
if(is_last_data_entry(data))
break;
}
}