Skip to content

Instantly share code, notes, and snippets.

@SF-Zhou
Created December 22, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SF-Zhou/ffa48c4fd200e2f0dcdda01a71c16ae7 to your computer and use it in GitHub Desktop.
Save SF-Zhou/ffa48c4fd200e2f0dcdda01a71c16ae7 to your computer and use it in GitHub Desktop.
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