C++简单实现生产者与消费者模式


#include 
#include 
#include 
#include 
#include 

std::queue buffer;  // 共享缓冲区
const int bufferSize = 5;  // 缓冲区大小

std::mutex mtx;  // 互斥锁
std::condition_variable cv_producer, cv_consumer;  // 条件变量

void Producer()
{
    for (int i = 1; i <= 10; ++i) {
        std::unique_lock lock(mtx);  // 获取互斥锁
        
        // 如果缓冲区已满,则等待消费者消耗数据
        while (buffer.size() >= bufferSize)
            cv_producer.wait(lock);
        
        buffer.push(i);
        std::cout << "Produced: " << i << std::endl;
        
        cv_consumer.notify_one();  // 通知消费者可以消费数据
    }
}

void Consumer()
{
    for (int i = 1; i <= 10; ++i) {
        std::unique_lock lock(mtx);  // 获取互斥锁
        
        // 如果缓冲区为空,则等待生产者生产数据
        while (buffer.empty())
            cv_consumer.wait(lock);
        
        int data = buffer.front();
        buffer.pop();
        std::cout << "Consumed: " << data << std::endl;
        
        cv_producer.notify_one();  // 通知生产者可以生产数据
    }
}

int main()
{
    std::thread producerThread(Producer);
    std::thread consumerThread(Consumer);
    
    producerThread.join();
    consumerThread.join();

    return 0;
}

你可能感兴趣的:(c++,开发语言,算法)