生產者和消費者模式(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 }