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