Last active
May 30, 2018 07:32
-
-
Save Bktero/740b52ebb4d9d3251f2003df20a67661 to your computer and use it in GitHub Desktop.
[C++11] Example of producer/consumer threads sharing data thanks to a queue protected by a mutex
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 <iostream> | |
#include <mutex> | |
#include <queue> | |
#include <sstream> | |
#include <thread> | |
int main(int, char*[]) { | |
std::queue<std::string> queue; | |
std::mutex mutex; | |
// Producer | |
std::thread producer([&]() { | |
auto produce = [&](const char* message) { | |
std::stringstream stream; | |
stream << message; | |
auto element = stream.str(); | |
std::cout << "Pushing " << message << std::endl; | |
mutex.lock(); | |
queue.push(element); | |
mutex.unlock(); | |
}; | |
produce("hello, world"); | |
produce("bye bye!"); | |
produce(":)"); | |
}); | |
// Consumer | |
std::thread consumer([&]() { | |
while (true) { | |
if(not queue.empty()) { | |
mutex.lock(); | |
auto message = queue.front(); | |
queue.pop(); | |
mutex.unlock(); | |
std::cout << "Received = " << message << std::endl; | |
} | |
} | |
}); | |
// Main | |
producer.join(); | |
consumer.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment