温馨提示×

C++循环队列的多线程应用案例

c++
小樊
87
2024-07-14 10:24:27
栏目: 编程语言

循环队列在多线程应用中经常用于实现生产者消费者模型。下面是一个简单的C++多线程应用案例,利用循环队列实现生产者消费者模型:

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

const int QUEUE_SIZE = 10;

std::queue<int> q;
std::mutex mtx;
std::condition_variable cv;

void producer() {
    for (int i = 0; i < 100; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, []{ return q.size() < QUEUE_SIZE; });
        q.push(i);
        lock.unlock();
        cv.notify_all();
    }
}

void consumer() {
    for (int i = 0; i < 100; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, []{ return !q.empty(); });
        int val = q.front();
        q.pop();
        std::cout << "Consumed: " << val << std::endl;
        lock.unlock();
        cv.notify_all();
    }
}

int main() {
    std::thread prod_thread(producer);
    std::thread cons_thread(consumer);

    prod_thread.join();
    cons_thread.join();

    return 0;
}

在这个案例中,我们使用一个循环队列q来存储生产者产生的数据,队列的最大容量为QUEUE_SIZE。生产者线程不断向队列中添加数据,如果队列已满,则等待消费者线程消费数据;消费者线程不断从队列中取出数据进行消费,如果队列为空,则等待生产者线程生产数据。

通过使用互斥量mtx和条件变量cv,我们实现了线程间的同步和通信。生产者线程在生产数据时会获取互斥量,然后判断队列是否已满,如果已满则等待消费者线程通知;消费者线程在消费数据时会获取互斥量,然后判断队列是否为空,如果为空则等待生产者线程通知。

0