Skip to content

Instantly share code, notes, and snippets.

@iikuy
Last active March 18, 2024 19:55
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iikuy/8115191 to your computer and use it in GitHub Desktop.
producer-consumer in C++11
#include <thread>
#include <iostream>
#include <queue>
std::mutex mx;
std::condition_variable cv;
std::queue<int> q;
bool finished = false;
void producer(int n) {
for(int i=0; i<n; ++i) {
{
std::lock_guard<std::mutex> lk(mx);
q.push(i);
std::cout << "pushing " << i << std::endl;
}
cv.notify_all();
}
{
std::lock_guard<std::mutex> lk(mx);
finished = true;
}
cv.notify_all();
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lk(mx);
cv.wait(lk, []{ return finished || !q.empty(); });
while (!q.empty()) {
std::cout << "consuming " << q.front() << std::endl;
q.pop();
}
if (finished) break;
}
}
int main() {
std::thread t1(producer, 10);
std::thread t2(consumer);
t1.join();
t2.join();
std::cout << "finished!" << std::endl;
}
@dayashankerprasad
Copy link

How producer will come to know that consumer has done its job in case consumer is scheduled for long time? This situation may arise as below

  1. producer thread scheduled at first and all the data pushed to queue.
  2. consumer thread is working and consumed all the data but still running.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment