Created
June 23, 2015 07:55
-
-
Save carlchen0928/bc0fe5ef65079ac3405a to your computer and use it in GitHub Desktop.
simple consumer and producer
This file contains hidden or 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
| #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