Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ readqueue

作者:狂刀血斧   发布日期:2025-04-29   浏览:87

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

class ReadQueue {
public:
    void enqueue(int value) {
        std::lock_guard<std::mutex> lock(mtx);
        queue.push(value);
        cond.notify_one(); // Notify one waiting thread
    }

    int dequeue() {
        std::unique_lock<std::mutex> lock(mtx);
        cond.wait(lock, [this] { return !queue.empty(); }); // Wait until the queue is not empty
        int value = queue.front();
        queue.pop();
        return value;
    }

private:
    std::queue<int> queue;
    std::mutex mtx;
    std::condition_variable cond;
};

void producer(ReadQueue& q, int num_items) {
    for (int i = 0; i < num_items; ++i) {
        q.enqueue(i);
        std::cout << "Produced: " << i << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate work
    }
}

void consumer(ReadQueue& q, int num_items) {
    for (int i = 0; i < num_items; ++i) {
        int value = q.dequeue();
        std::cout << "Consumed: " << value << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(150)); // Simulate work
    }
}

int main() {
    ReadQueue q;
    const int num_items = 10;

    std::thread t1(producer, std::ref(q), num_items);
    std::thread t2(consumer, std::ref(q), num_items);

    t1.join();
    t2.join();

    return 0;
}

解释说明

  1. ReadQueue:

    • 使用了 std::queue 来存储数据。
    • 使用了 std::mutex 来保证线程安全。
    • 使用了 std::condition_variable 来实现生产者和消费者之间的同步。
  2. 方法 enqueue:

    • 将元素加入队列,并通知等待的线程。
  3. 方法 dequeue:

    • 等待直到队列不为空,然后取出并返回队列中的第一个元素。
  4. 函数 producerconsumer:

    • producer 函数模拟生产者,向队列中添加数据。
    • consumer 函数模拟消费者,从队列中取出数据。
  5. 主函数 main:

    • 创建一个 ReadQueue 对象。
    • 启动两个线程,分别运行 producerconsumer 函数。
    • 使用 join 方法等待两个线程结束。

上一篇:c++ 面向对象

下一篇:c++运算符优先级由高到低

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ vector 清空

c++ tcp

c++ gcd函数

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站