Skip to content

Instantly share code, notes, and snippets.

@ender233
Created July 31, 2017 04:29
Show Gist options
  • Save ender233/1556628abfc5e0c9aaad4694c214183e to your computer and use it in GitHub Desktop.
Save ender233/1556628abfc5e0c9aaad4694c214183e to your computer and use it in GitHub Desktop.
condition_variable
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;
int main()
{
// lock
std::queue<int> produced_nums;
std::mutex m;
std::condition_variable con_var;
// variable
bool done = false;
bool notified = false;
std::thread producer([&](){
for(int i=0; i<5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::unique_lock<std::mutex> lock(m);
std::cout<<"producing "<<i<<endl;
produced_nums.push(i);
notified = true;
// con_var.notify_all();
con_var.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(2));
}
done = true;
con_var.notify_all();
});
std::thread consumer([&]() {
std::unique_lock<std::mutex> lock(m);
while(!done) {
//con_var.wait(lock, [&]{return notified;});
if(!notified) con_var.wait(lock);
while(!produced_nums.empty()) {
std::cout<<"consuming " <<produced_nums.front()<<" consumer1"<<endl;
produced_nums.pop();
}
std::cout<<"thread id: 1 "<<"wake up"<<std::endl;
notified = false;
}
notified = true;
});
std::thread consumer2([&]() {
std::unique_lock<std::mutex> lock(m);
while(!done) {
std::this_thread::sleep_for(std::chrono::seconds(1));
//con_var.wait(lock, [&]{return notified;});
if(!notified) con_var.wait(lock);
while(!produced_nums.empty()) {
std::cout<<"consuming " <<produced_nums.front()<<" consumer2"<<endl;
produced_nums.pop();
}
std::cout<<"thread id: 2 "<<"wake up"<<std::endl;
notified = false;
}
notified = true;
});
producer.join();
consumer.join();
consumer2.join();
/*
std::this_thread::sleep_for(1s);
std::cout<<"id1:"<<consumer.get_id()<<endl;
std::cout<<"id2:"<<consumer2.get_id()<<std::endl;
std::cout<<"producer:"<<producer.get_id()<<std::endl;
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment