量化交易之One Piece篇 - 线程安全队列- ThreadSafeQueue

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

template<typename T>
class ThreadSafeQueue {
private:
    std::queue<T> queue_;
    mutable std::mutex mutex_;
    std::condition_variable cond_;

public:
    void Push(const T& value) {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            queue_.push(value);
        }
        cond_.notify_one();  // 通知等待中的消费者
    }

    T Pop() {
        std::unique_lock<std::mutex> lock(mutex_);
        cond_.wait(lock, [this] { return !queue_.empty(); });  // 等待直到队列非空
        T value = queue_.front();
        queue_.pop();
        return value;
    }

    bool Empty() const {
        std::shared_lock<std::mutex> lock(mutex_);
        return queue_.empty();
    }
};
#include <memory>
#include <onepiece/datacore/DataCore.h>

#include <memory>
#include <thread>

#include <onepiece/templates/ThreadSafeQueue.h>

using namespace std;

int main(int argc, const char *argv[]) {

    ThreadSafeQueue<int> queue;

    // 生产者线程
    std::thread producerThread([&queue] {
        for (int i = 1; i <= 5; ++i) {
            queue.Push(i);
            std::this_thread::sleep_for(std::chrono::seconds(1));
            // std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    });

    // 消费者线程
    std::thread consumerThread([&queue] {
        for (int i = 1; i <= 5; ++i) {
            int value = queue.Pop();
            std::cout << "Consumed: " << value << std::endl;
        }
    });

    producerThread.join();
    consumerThread.join();
   
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值