CodexBloom - Programming Q&A Platform

implementing std::thread and std::condition_variable in C++20 for Producer-Consumer solution

👀 Views: 34 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
c++20 multithreading concurrency cpp

I'm learning this framework and Does anyone know how to I'm working on a personal project and I'm stuck on something that should probably be simple. I'm working with some unexpected behavior while implementing a simple producer-consumer question using `std::thread` and `std::condition_variable` in C++20. The goal is to have a producer thread that generates data and a consumer thread that processes it. However, I'm working with a scenario where the consumer sometimes tries to access the data before the producer has finished writing it, leading to incorrect output. Here is a simplified version of my code: ```cpp #include <iostream> #include <thread> #include <queue> #include <condition_variable> #include <chrono> std::queue<int> dataQueue; std::mutex queueMutex; std::condition_variable cv; bool done = false; void producer() { for (int i = 0; i < 10; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulating work std::lock_guard<std::mutex> lock(queueMutex); dataQueue.push(i); std::cout << "Produced: " << i << '\n'; cv.notify_one(); } { // Notify consumer that production is done std::lock_guard<std::mutex> lock(queueMutex); done = true; cv.notify_one(); } } void consumer() { while (true) { std::unique_lock<std::mutex> lock(queueMutex); cv.wait(lock, [] { return !dataQueue.empty() || done; }); if (!dataQueue.empty()) { int value = dataQueue.front(); dataQueue.pop(); lock.unlock(); // Unlock before processing std::cout << "Consumed: " << value << '\n'; } else if (done) { break; // Exit if done } } } int main() { std::thread producerThread(producer); std::thread consumerThread(consumer); producerThread.join(); consumerThread.join(); return 0; } ``` The output sometimes shows "Consumed: 0" followed by "Consumed: 1" even though I expect them to appear in order after production. I need to seem to figure out why the consumer is accessing data prematurely. I've tried adding additional locks around the queue access, but it doesn't seem to solve the scenario. What am I missing? Is there a better way to synchronize the producer and consumer in C++20? I verified that I'm using the latest GCC version 11.2.0. Any insights would be greatly appreciated! I'd really appreciate any guidance on this. This is my first time working with Cpp 3.11. Am I approaching this the right way? I'm developing on Windows 10 with Cpp. Thanks for any help you can provide!