在C ++中构建多线程工作队列(消费者/生产者) [英] Building a multithreaded work-queue (consumer/producer) in C++
问题描述
我有以下场景:我有一个线程,应该填充一个
容器与成对的整数(实质上,任务描述),我有一个大的
工作线程数(8-16),它应该从这个容器中取出元素并执行
一些工作。
I have the following scenario: I have a single thread that is supposed to fill a container with pairs of integers (in essence, task descriptions), and I have a large number of worker threads (8-16) that should take elements from this container and perform some work.
我认为问题可以很容易地通过阻塞队列解决 - 例如
I thought the problem could be easily solved by a blocking queue -- e.g. on item-removal, threads synchronize access to the queue, and sleep if there is no data available.
我(可能是错误的)假设这样的东西应该存在于队列中,如果没有可用的数据, STL或在boost,但我找不到任何东西。
I (perhaps wrongly) assumed that something like this should exist in the STL or in boost, but I was unable to find anything.
我真的要自己实现这个东西吗?看起来像这样常见的情况...
Do I actually have to implement that thing myself ? It seems like such a common scenario...
推荐答案
如果你自己实现它,实现应该是一个相当简单的组合
If you do implement it yourself, the implementation should be a fairly straightforward combination of a semaphore, a mutex, and a queue object.
这里有一些伪代码:
Produce{
pthread_mutex_lock(&mutex);
queue.push_back(someObjectReference);
pthread_mutex_unlock(&mutex);
sem_post(&availabilitySem);
}
Consume{
sem_wait(&availabilitySem);
pthread_mutex_lock(&mutex);
queue.pop_front(someObjectReference);
pthread_mutext_unlock(&mutex);
}
这篇关于在C ++中构建多线程工作队列(消费者/生产者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!