生产者消费者模式通过共享缓冲区、互斥锁和条件变量实现多线程同步,解决数据生产与消费速度不匹配问题,C++中利用queue、mutex和condition_variable完成线程间协调,确保线程安全与高效通信。

生产者消费者模式是多线程编程中的经典问题,用于解决生产数据与消费数据速度不匹配的问题。在C++中,通常使用互斥锁(std::mutex)、条件变量(std::condition_variable)和队列(std::queue)来实现线程间的同步与互斥。
要实现生产者消费者模型,需要以下几个关键元素:
下面是一个基于固定大小缓冲区的生产者消费者模型实现:
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::queue<int> buffer;
std::mutex mtx;
std::condition_variable not_empty;
std::condition_variable not_full;
const int max_buffer_size = 5;
void producer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
not_full.wait(lock, []() { return buffer.size() < max_buffer_size; });
buffer.push(i);
std::cout << "生产者 " << id << " 生产: " << i << std::endl;
not_empty.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<std::mutex> lock(mtx);
not_empty.wait(lock, []() { return !buffer.empty(); });
int value = buffer.front();
buffer.pop();
std::cout << "消费者 " << id << " 消费: " << value << std::endl;
not_full.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
主函数中启动多个生产者和消费者线程:
立即学习“C++免费学习笔记(深入)”;
int main() {
std::thread p1(producer, 1);
std::thread p2(producer, 2);
std::thread c1(consumer, 1);
std::thread c2(consumer, 2);
p1.join();
p2.join();
c1.join();
c2.join();
return 0;
}
该实现中几个重要细节:
这种模式广泛应用于任务调度、消息队列、日志处理等场景。可以根据需求进行扩展:
基本上就这些。掌握这个模型对理解多线程同步机制非常有帮助。
以上就是C++如何实现生产者消费者模式_C++多线程同步与互斥经典案例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号