c++各个线程中数据交互的方法----安全队列

#pragma once
#include<queue>
#include<mutex>
#include<condition_variable>
template<typename T>
class CThreadsafe_queue
{
public:
    CThreadsafe_queue() {}
    ~CThreadsafe_queue() {

    };
    void Relese()
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        run_flag = false;
        QueueConditionalVariable.notify_all();
    }
    void Push(T NewData)
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        Que.push(std::move(NewData));
        QueueConditionalVariable.notify_one();
    }
    bool wait_pop(T& Data)
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        QueueConditionalVariable.wait(unl, [this] {return !Que.empty() || !run_flag; });
        if(!run_flag )
            return false;
        Data = std::move(Que.front());
        Que.pop();
        return true;
    }
    bool wait_pop(T& Data, int msec) 
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        if (!QueueConditionalVariable.wait_for(unl, std::chrono::microseconds(msec), [this] {return !Que.empty() || !run_flag; }))
        {
            return false;
        }
        if(!run_flag )
            return false;
        Data = std::move(Que.front());
        Que.pop();
        return true;
    }
    bool TryPop(T& Data)
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        if (Que.empty())
            return false;
        Data = std::move(Que.front());
        Que.pop();
    }
    unsigned int GetSize()
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        return Que.size();
    }
    std::shared_ptr<T> wait_pop()
    {
        std::unique_lock<std::mutex> unl(QueueMutex);
        QueueConditionalVariable.wait(unl, [this] {return !Que.empty() || !run_flag;});
        if(!run_flag || Que.size() == 0)
            return nullptr;
        std::shared_ptr<T> res(std::make_shared<T>(std::move(Que.front())));
        Que.pop();
        return res;
    }
private:
    bool run_flag = true;
    std::mutex QueueMutex;
    std::condition_variable QueueConditionalVariable;
    std::queue<T> Que;
};

使用方法

1.在全局类里面定义初始化queue       CThreadsafe_queue<int> IntQueue; 

2.在一个线程中:

IntQueue.push(1);

3.在另一个线程中:

  int i;

while(1)

{

        IntQueue.waitpop(i);

         //  逻辑处理数据

}

每次循环都会阻塞在IntQueue.waitpop(i);这里直到有数据后才进行后面操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值