Skip to content

Instantly share code, notes, and snippets.

@patelpreet422
Last active April 26, 2018 11:45
Show Gist options
  • Save patelpreet422/cf50e76842004f2f8aa9b84844ac0366 to your computer and use it in GitHub Desktop.
Save patelpreet422/cf50e76842004f2f8aa9b84844ac0366 to your computer and use it in GitHub Desktop.
Producer consumer problem implementation in C++.
//run following program by using following command
//compile: g++ -std=c++17 -pthread producer_consumer.cpp
//run: ./a.out (on linux machine)
//run: a.exe (on windows machine)
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
using namespace std::chrono_literals;
int main(){
std::queue<int> queue;
std::mutex mu;
std::condition_variable cv;
std::thread producer([&](){
for(int i = 1; i <= 10; ++i){
std::unique_lock<std::mutex> locker(mu);
queue.push(i);
std::cout << "Pushing: " << i << '\n';
locker.unlock();
cv.notify_one();
std::this_thread::sleep_for(1s);
}
});
std::thread consumer([&](){
size_t length = 10;
while(length != 0){
std::unique_lock<std::mutex> locker(mu);
cv.wait(locker, [&](){return !queue.empty();});
std::cout << "Consuming: " << queue.back() << '\n';
queue.pop();
locker.unlock();
--length;
}
});
producer.join();
consumer.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment