Last active
September 24, 2023 19:14
-
-
Save barron9/94a80b3052d54370d5dfc57c7f60c188 to your computer and use it in GitHub Desktop.
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 <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