gpt4 book ai didi

c++ - 经典生产者消费者线程

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:25 24 4
gpt4 key购买 nike

Classical producer consumer problem .生产者在 itemCount == BUFFER_SIZE 时休眠,当它下降时再次唤醒。但是一旦 itemCount 增长,生产者线程就会进入休眠状态。它怎么知道 itemCount 已经下降并且需要 wakeup

最佳答案

在伪代码中,生产者是这样的:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com