在 Classical producer consumer problem 。当 itemCount == BUFFER_SIZE
时,生产者会休眠,而当它宕机时,生产者会再次醒来。但是一旦 itemCount
增大,生产者线程就会进入休眠状态。它如何知道 itemCount
已下降并且需要唤醒
?
最佳答案
在伪代码中,生产者类似于:
void producer_thread()
{
while(true)
queue.push( produce() );
}
所以考虑队列推送方法(我在这里使用了pthreads,但相同的逻辑也适用于其他库)
void SynchronizedQueue::push(Item const &i)
{
pthread_mutex_lock(&mutex);
// queue is full, so wait for consumer
while (queue.size() == BUFFER_SIZE)
pthread_cond_wait(&condition, &mutex);
// when we get here, the queue has space
this->queue.push_back(i);
// make sure we wake a sleeping consumer
if (queue.size() == 1)
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
}
以及消费者使用的pop方法:
Item SynchronizedQueue::pop()
{
pthread_mutex_lock(&mutex);
// wait for something to do
while (queue.size() == 0)
pthread_cond_wait(&condition, &mutex);
// if we get here, we have some work
Item tmp = queue.front();
// make sure we wake a sleeping producer
if (queue.size() == BUFFER_SIZE)
pthread_cond_signal(&condition)
queue.pop_front();
pthread_mutex_unlock(&mutex);
return tmp;
}
关于c++ - 经典的生产者消费者线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11180134/