生产者和消费者模式(Consumer + Producer model)
用于把耗时操作(生产线程),分配给一个或者多个额外线程执行(消费线程),从而提高生产线程的响应速度(并发能力)
定义
typedef std::unique_ptr<Work> WorkPtr;
std::queue<WorkPtr> work_queue;
uv_mutex_t mutex;
uv_cond_t cond;
生产
//adding new work
WorkPtr newWork(new Work);
uv_mutex_lock(&mutex);
work_queue.push(std::move(new_work));
uv_cond_signal(&cond);
uv_mutex_unlock(&mutex);
消费
while(true)
{
//copying work that has to be done
uv_mutex_lock(&mutex);
while(work_queue.empty())
{
uv_cond_wait(&cv, &mutex);
}
WorkPtr work;
work.swap(work_queue.front());
work_queue.pop();
uv_mutex_unlock(&mutex);
//doing work ...
}