c++多线程——基于锁和条件变量的前程安全队列

实现了一个模板类。

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清欢_小铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值