Last active
April 26, 2018 11:45
-
-
Save patelpreet422/cf50e76842004f2f8aa9b84844ac0366 to your computer and use it in GitHub Desktop.
Producer consumer problem implementation in C++.
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
//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