Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++11 Producer + Consumer
#include <chrono>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
std::mutex mutex;
std::queue<int> candidates;
std::condition_variable condition;
void produce() {
for (int i = 0;; ++i) {
// complex manufacture
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::unique_lock<std::mutex> lock(mutex);
candidates.push(i);
}
condition.notify_one();
}
}
void consume() {
while (true) {
int value;
{
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, [] { return !candidates.empty(); });
value = candidates.front();
candidates.pop();
}
// complex calculation
std::this_thread::sleep_for(std::chrono::seconds(4));
auto result = value * value;
std::cout << "Power of " << value << " is " << result << std::endl;
}
}
int main() {
std::thread producer(produce);
std::vector<std::thread> consumers;
for (int i = 0; i < 4; ++i) {
consumers.emplace_back(consume);
}
producer.join();
for (auto &consumer: consumers) {
consumer.join();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.