#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);这里直到有数据后才进行后面操作
1316

被折叠的 条评论
为什么被折叠?



