consumer_producer
// Compiled with: g++ -Wall -std=c++14 -pthread
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <queue>
#include <thread>
#include <vector>
using namespace std;
priority_queue<int> pqueue;
mutex m;
condition_variable var;
bool finished = false;
const int max_count = 5;
void producer() {
vector<int> items = { 1, 2, 3, 4, 5, 6 ,7, 8, 9, 10 };
size_t index = 0;
while (index < items.size()) {
unique_lock<mutex> lk(m);
while(pqueue.size() < max_count && index < items.size()) {
pqueue.push(items[index]);
index++;
var.notify_all();
}
cout << "wait to drain .. " << endl;
var.wait(lk, [] { return pqueue.size() < max_count;});
}
unique_lock<mutex> lk(m);
finished = true;
var.notify_all();
}
void worker_thread() {
while(1) {
unique_lock<mutex> lk(m);
var.wait(lk, []{return finished || !pqueue.empty();});
cout << "awake: " << endl;
while(!pqueue.empty()) {
int val = pqueue.top();
pqueue.pop();
cout << "processed: " << val << endl;
}
//signal that queue is drained
var.notify_one();
if (finished) break;
}
}
int main(){
cout << "Hello, World!" << endl;
thread t1(worker_thread);
thread t2(producer);
t2.join();
t1.join();
cout << "This is the End" << endl;
return 0;
}