Last active
October 3, 2018 19:05
-
-
Save adler3d/1cfee67a43f2922f64b9a205a5610d67 to your computer and use it in GitHub Desktop.
producer-consumer in C++11
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 <thread> | |
#include <iostream> | |
#include <queue> | |
#include <mutex> | |
#include <atomic> | |
#include <string> | |
#include <condition_variable> | |
using namespace std; | |
struct t_blocking_queue{ | |
std::mutex m; | |
std::condition_variable cv; | |
std::queue<string> q; | |
void push(const string&s){ | |
{std::lock_guard<std::mutex> g(m);q.push(s);} | |
cv.notify_all(); | |
} | |
string pop(){ | |
std::unique_lock<std::mutex> g; | |
auto cond=[&]{return !q.empty();}; | |
for(;;){ | |
std::unique_lock<std::mutex> lk(m); | |
cv.wait(lk,cond); | |
if(cond()){g=std::move(lk);break;} | |
} | |
string s=q.front(); | |
q.pop(); | |
return s; | |
} | |
}; | |
t_blocking_queue bq; | |
void producer(int n) { | |
for(int i=0; i<n; ++i) { | |
bq.push(std::to_string(i)); | |
} | |
bq.push("stop"); | |
} | |
void consumer() { | |
for(;;){ | |
auto s=bq.pop(); | |
if(s=="stop")return; | |
cout<<s<<"\n"; | |
} | |
} | |
int main() { | |
std::thread t1(producer, 10); | |
std::thread t2(consumer); | |
t1.join(); | |
t2.join(); | |
std::cout << "finished!" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment