Skip to content

Instantly share code, notes, and snippets.

@barron9
Last active September 24, 2023 19:14
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 barron9/94a80b3052d54370d5dfc57c7f60c188 to your computer and use it in GitHub Desktop.
Save barron9/94a80b3052d54370d5dfc57c7f60c188 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
std::queue<int> dataQueue;
std::mutex mtx;
std::condition_variable cv;
const int maxQueueSize = 10; // Maximum queue size before backpressure is applied
void producer() {
for (int i = 0; i < 200; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate data production
std::unique_lock<std::mutex> lock(mtx);
while (dataQueue.size() >= maxQueueSize) {
std::cout << "Queue is full, applying backpressure...\n";
cv.wait(lock); // Wait for space in the queue
}
dataQueue.push(i);
std::cout << "Produced: " << i << "\n";
cv.notify_all(); // Notify consumers that data is available
}
}
void consumer() {
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1200)); // Simulate data processing
std::unique_lock<std::mutex> lock(mtx);
while (dataQueue.empty()) {
std::cout << "Queue is empty, waiting for data...\n";
cv.wait(lock); // Wait for data to be available
}
int data = dataQueue.front();
dataQueue.pop();
std::cout << "Consumed: " << data << "\n";
cv.notify_all(); // Notify producers that space is available in the queue
}
}
int main() {
std::thread producerThread(producer);
std::thread consumerThread(consumer);
producerThread.join();
consumerThread.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment