Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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);
std::cout << "pushing " << i << std::endl;
std::lock_guard<std::mutex> lk(mx);
finished = true;
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;
if (finished) break;
int main() {
std::thread t1(producer, 10);
std::thread t2(consumer);
std::cout << "finished!" << std::endl;
Copy link

razin1105112 commented Apr 5, 2017

thanks for your contribution :).but thread switching is very it correct??

Copy link

palucki commented Sep 5, 2017

Hi folk!
You are missing

#include <mutex>
#include <condition_variable> 

for the example to work seamlessly.
Regards ;)

Copy link

amithld commented Aug 13, 2018

Hello All,

Could you please explain me line no 30 ( cv.wait(lk, []{ return finished || !q.empty(); }); ) and how does condition variable knows which threads are using it and how it notifies other thread, or if you could explain me condition variable usage in this program?


Copy link

anibalanto commented Oct 10, 2018

If you quit line 14:

std::lock_guard<std::mutex> lk(mx);

the producer don't wait to consumer finishes.

Copy link

dayashankerprasad commented Sep 6, 2020

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