Skip to content

Instantly share code, notes, and snippets.

@carlchen0928
Created June 23, 2015 07:55
Show Gist options
  • Save carlchen0928/bc0fe5ef65079ac3405a to your computer and use it in GitHub Desktop.
Save carlchen0928/bc0fe5ef65079ac3405a to your computer and use it in GitHub Desktop.
simple consumer and producer
#include <iostream>
#include <stdio.h>
#include <stack>
#include <vector>
#include <string>
#include <exception>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <queue>
using namespace std;
mutex mtx;
condition_variable cv;
queue<int> q;
int a = 0;
void process()
{
while (true)
{
unique_lock<mutex> ul(mtx);
while (q.empty())
{
cv.wait(ul);
}
int t = q.front();
q.pop();
ul.unlock();
cout << "process " << t << endl;
}
}
void producer()
{
lock_guard<mutex> lg(mtx);
q.push(a);
cout << "producer " << a << endl;
a++;
cv.notify_one();
}
int main()
{
thread t1(process);
// thread t2(producer);
// t2.join();
for (int i = 0; i < 10; i++)
producer();
t1.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment