code for the classic producer consumer problem
Utilisateur anonyme
Did not get a chance to finish it, but it would be something like: #include #include #include #include #include #include std::queue queue; std::mutex mutex; std::condition_variable cond_var; void producer(int id) { for (int i = 0; i < 10; ++i) { std::unique_lock lock(mutex); queue.push(i); std::cout << "Producer " << id << " produced " << i << std::endl; lock.unlock(); cond_var.notify_one(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void consumer(int id) { for (int i = 0; i < 10; ++i) { std::unique_lock lock(mutex); cond_var.wait(lock, []{ return !queue.empty(); }); int value = queue.front(); queue.pop(); std::cout << "Consumer " << id << " consumed " << value << std::endl; lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } } int main() { std::thread producer1(producer, 1); std::thread consumer1(consumer, 1); std::thread producer2(producer, 2); std::thread consumer2(consumer, 2); producer1.join(); consumer1.join(); producer2.join(); consumer2.join(); return 0; }