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

标签 c++ multithreading producer-consumer

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/

相关文章:

C++进程类错误

c++ - 无限循环多线程

c++ - C/C++ 宏扩展 : from two to four parameters

python - 图像变化检测照度变化和小偏移的问题

c++ - 为什么位模式与 std::bitset 的使用不匹配

c# - 使用 Dispose() 或终结器来清理托管线程?

Java - 同步方法/ block

java - 使单个线程执行完成

java - 使用核心 api 消费后 HornetQ 消息仍保留在队列中

c# - 如何批量消费 BlockingCollection<T>