condition variable wait unlocks mutex c 2b 2b

Solutions on MaxInterview for condition variable wait unlocks mutex c 2b 2b by the best coders in the world

showing results for - "condition variable wait unlocks mutex c 2b 2b"
Jayson
18 Jun 2017
1std::mutex mutex;
2std::queue buffer;              
3std::condition_variable buffer_cond;
4
5void data_preparation_thread()
6{
7    while(has_data_to_prepare())                //--  (1)    
8    {
9      buffer_data data = prepare_data();
10      std::lock_quard lock(mutex);  //--  (2) 
11      buffer.push(data);                        
12      buffer_cond.notify_one();                 //-- (3)  
13    }
14}
15
16void data_processing_thread()
17{
18    while(true)
19    {
20      std::unique_lock lock(mutex);              //-- (4)  
21      buffer_cond.wait(lock, []{return ! buffer.empty()})    //-- (5)   
22      buffer_data data = buffer.front();
23      buffer.pop();
24      lock.unlock();                                         //-- (6)   
25      process(data);
26      if(is_last_data_entry(data)) 
27          break;         
28    }  
29}
30
similar questions