实现了一个模板类。
#pragma once
#include <exception>
#include <thread>
#include <mutex>
#include <queue>
#include <utility>
#include <condition_variable>
#include <memory>
using namespace std;
template<typename T>
class tsafe_queue {
private:
mutex m;
queue<T> data;
condition_variable c;
public:
tsafe_queue() {}
void push(T a_value) {
lock_guard<mutex> lock(m);
data.push(move(a_value));
c.notify_one();
}
void wait_and_pop(T& value) {
unique_lock<mutex> lk(m);
c.wait(lk, [this] {return !data.empty(); });
value = move(data.front());
data.pop();
}
shared_ptr<T> wait_and_pop() {
unique_lock<mutex> lk(m);
c.wait(lk, [this] {return !data.empty(); });
shared_ptr<T> res(make_shared<T>(move(data.front())));
data.pop();
return res;
}
bool try_pop(T& value) {
lock_guard<mutex> lock(m);
if (data.empty()) {
return false;
}
value = move(data.front());
data.pop();
return true;
}
shared_ptr<T> try_pop() {
lock_guard<mutex> lock(m);
if (data.empty()) {
return shared_ptr<T>();
}
shared_ptr<T> res(make_shared<T>(move(data.front())));
data.pop();
return res;
}
bool empty() const {
lock_guard<mutex> lock(m);
return data.empty();
}
};
其中,wait_and_pop有两个重载,等待队列有数据才会返回,try_pop是立刻返回,没有数据时,返回false和空指针。
单线程测试
// 简单线程池.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include "tsafe_queue.h"
int main()
{
tsafe_queue<int> q;
q.push(1);
int i;
q.try_pop(i);
std::cout << i;
}