Last active
July 11, 2018 18:37
-
-
Save bexp/f596a30be790367e851010d3cf20e522 to your computer and use it in GitHub Desktop.
consumer_producer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment