Skip to content

Instantly share code, notes, and snippets.

@Bktero
Last active May 30, 2018 07:32
Show Gist options
  • Save Bktero/740b52ebb4d9d3251f2003df20a67661 to your computer and use it in GitHub Desktop.
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
#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