Skip to content

Instantly share code, notes, and snippets.

@andres7293
Last active October 27, 2023 14:57
Show Gist options
  • Save andres7293/e128c19861cf2a353540aa226db37733 to your computer and use it in GitHub Desktop.
Save andres7293/e128c19861cf2a353540aa226db37733 to your computer and use it in GitHub Desktop.
Code snippet with elementary stuff needed to send messages throug a queue to a thread to dispatch tasks.
#include <iostream>
#include <thread>
#include <future>
#include <functional>
#include <queue>
#include <format>
#include <csignal>
using namespace std::chrono_literals;
template<typename T>
void Consumer(std::mutex& mutex, std::queue<T>& queue) {
while (1) {
mutex.lock();
if (!queue.empty()) {
auto msg = queue.front();
std::cout << msg << std::endl;
queue.pop();
}
mutex.unlock();
std::this_thread::sleep_for(5ms);
}
}
template<typename T>
void Producer(std::mutex& mutex, std::queue<T>& queue) {
int count = 0;
while (1) {
mutex.lock();
queue.push(count++);
mutex.unlock();
std::this_thread::sleep_for(100ms);
}
}
std::queue<int> queue;
int main() {
std::mutex mutex;
auto producer = std::thread(Producer<int>, std::ref(mutex), std::ref(queue));
auto consumer_1 = std::thread(Consumer<int>, std::ref(mutex), std::ref(queue));
auto consumer_2 = std::thread(Consumer<int>, std::ref(mutex), std::ref(queue));
signal(SIGINT, [](int sig) {
std::cout << std::format("SIGINT - queue.size()={}\n", queue.size());
abort();
});
consumer_1.detach();
consumer_2.detach();
producer.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment