古典生产者消费者线程 [英] classical producer consumer threading

查看:151
本文介绍了古典生产者消费者线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

古典生产者消费者问题中。当 itemCount == BUFFER_SIZE amd时,生产者睡眠,当它下降时再次唤醒。但是一旦 itemCount 成长,生产者线程就会进入休眠状态。如何知道 itemCount 已经下降,需要唤醒


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

  void producer_thread()
{
while(true)
queue.push(produce());
}

所以考虑队列推送方法(我在这里使用pthreads,同样的逻辑适用于其他库)

  void SynchronizedQueue :: push(Item const& i)
{
pthread_mutex_lock(& mutex);

//队列已满,因此等待消费者
while(queue.size()== BUFFER_SIZE)
pthread_cond_wait(& condition,& mutex);

//当我们到达这里时,队列有空间
this-> queue.push_back(i);

//确保我们唤醒睡眠消费者
if(queue.size()== 1)
pthread_cond_signal(& condition);

pthread_mutex_unlock(& mutex);
}

和消费者使用的pop方法:

 项目SynchronizedQueue :: pop()
{
pthread_mutex_lock(& mutex);

//等待某事要做
while(queue.size()== 0)
pthread_cond_wait(& condition,& mutex);

//如果我们到这里,我们有一些工作
Item tmp = queue.front();

//确保我们唤醒一个睡眠的生产者
if(queue.size()== BUFFER_SIZE)
pthread_cond_signal(& condition)

queue.pop_front();
pthread_mutex_unlock(&mutex);
return tmp;
}


In the Classical producer consumer problem. producer sleeps when itemCount == BUFFER_SIZE amd wakes up again when it goes down. But once itemCount grows up, producer thread is put to sleep. how can it know that itemCount has gone down and it needs to wakeup ?

解决方案

In pseudo-code the producer is something like:

void producer_thread()
{
    while(true)
        queue.push( produce() );
}

so consider the queue push method (I've used pthreads here, but the same logic applies with other libraries)

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);
}

and the pop method used by the consumer:

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;
}

这篇关于古典生产者消费者线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆