Created
December 22, 2018 15:38
-
-
Save SF-Zhou/ffa48c4fd200e2f0dcdda01a71c16ae7 to your computer and use it in GitHub Desktop.
C++11 Producer + Consumer
This file contains 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
#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