1. 生产者-消费者模型概述
生产者-消费者模型是操作系统和并发编程中最经典的同步问题之一。这个模型描述了两个不同类型的进程(或线程)——生产者和消费者,它们共享一个固定大小的缓冲区。生产者负责生成数据放入缓冲区,而消费者则从缓冲区取出数据进行消费。
在实际工程中,这个模型的应用场景非常广泛。比如在Web服务器中,工作线程从请求队列中取出任务进行处理;在日志系统中,日志生成线程将日志写入缓冲区,而日志写入线程从缓冲区读取日志写入磁盘;在视频播放器中,解码线程不断生成视频帧放入缓冲区,而渲染线程从缓冲区取出帧进行播放。
用C++实现这个模型有几个关键挑战:首先是线程安全问题,生产者和消费者可能同时访问缓冲区;其次是同步问题,当缓冲区满时生产者需要等待,缓冲区空时消费者需要等待;最后是性能问题,不合理的实现可能导致大量线程切换开销。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心数据结构与同步机制
2.1 环形缓冲区设计
在实现生产者-消费者模型时,我们通常使用环形缓冲区(Circular Buffer)作为共享数据结构。环形缓冲区是一种线性数据结构,其表现和用途与普通缓冲区一样,但有一个关键特性:当到达缓冲区末尾时,它会自动从缓冲区开头继续写入数据。
cpp复制template <typename T>
class CircularBuffer {
public:
explicit CircularBuffer(size_t size) :
buf_(std::unique_ptr<T[]>(new T[size])),
max_size_(size)
{}
// 其他成员函数...
private:
std::unique_ptr<T[]> buf_;
size_t head_ = 0;
size_t tail_ = 0;
const size_t max_size_;
bool full_ = false;
};
环形缓冲区的优势在于:
- 内存利用率高,不需要频繁分配释放内存
- 读写操作都是O(1)时间复杂度
- 实现相对简单,只需要维护头尾指针
2.2 同步原语选择
C++11之后的标准库提供了丰富的线程同步原语,我们需要根据场景选择最合适的组合:
- 互斥锁(mutex):保证对缓冲区的访问是互斥的
- 条件变量(condition_variable):用于线程间通知状态变化
- 原子操作(atomic):用于简单的状态标志
cpp复制std::mutex mtx;
std::condition_variable not_full;
std::condition_variable not_empty;
提示:避免直接使用裸锁,应该使用RAII包装器如std::unique_lock,确保异常安全。
3. 完整实现解析
3.1 线程安全环形缓冲区实现
我们先完善环形缓冲区的线程安全版本:
cpp复制template <typename T>
class ThreadSafeCircularBuffer {
public:
explicit ThreadSafeCircularBuffer(size_t size) :
buf_(std::unique_ptr<T[]>(new T[size])),
max_size_(size)
{}
void put(T item) {
std::unique_lock<std::mutex> lock(mtx_);
not_full_.wait(lock, [this](){ return !isFull(); });
buf_[head_] = item;
head_ = (head_ + 1) % max_size_;
full_ = head_ == tail_;
lock.unlock();
not_empty_.notify_one();
}
T get() {
std::unique_lock<std::mutex> lock(mtx_);
not_empty_.wait(lock, [this](){ return !isEmpty(); });
auto val = buf_[tail_];
tail_ = (tail_ + 1) % max_size_;
full_ = false;
lock.unlock();
not_full_.notify_one();
return val;
}
bool isEmpty() const { return (!full_ && (head_ == tail_)); }
bool isFull() const { return full_; }
size_t capacity() const { return max_size_; }
private:
std::mutex mtx_;
std::condition_variable not_full_;
std::condition_variable not_empty_;
std::unique_ptr<T[]> buf_;
size_t head_ = 0;
size_t tail_ = 0;
const size_t max_size_;
bool full_ = 0;
};
3.2 生产者与消费者线程实现
生产者线程的基本逻辑是不断生成数据并放入缓冲区:
cpp复制void producer(T
