栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

实现了一个模板类。

#pragma once
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
template
class tsafe_queue {
private:
	mutex m;
	queue data;
	condition_variable c;
public:
	tsafe_queue() {}
	void push(T a_value) {
		lock_guard lock(m);
		data.push(move(a_value));
		c.notify_one();
	}
	void wait_and_pop(T& value) {
		unique_lock lk(m);
		c.wait(lk, [this] {return !data.empty(); });
		value = move(data.front());
		data.pop();
	}
	shared_ptr wait_and_pop() {
		unique_lock lk(m);
		c.wait(lk, [this] {return !data.empty(); });
		shared_ptr res(make_shared(move(data.front())));
		data.pop();
		return res;
	}
	bool try_pop(T& value) {
		lock_guard lock(m);
		if (data.empty()) {
			return false;
		}
		value = move(data.front());
		data.pop();
		return true;
	}
	shared_ptr try_pop() {
		lock_guard lock(m);
		if (data.empty()) {
			return shared_ptr();
		}
		shared_ptr res(make_shared(move(data.front())));
		data.pop();
		return res;
	}
	bool empty() const {
		lock_guard lock(m);
		return data.empty();
	}
};

其中,wait_and_pop有两个重载,等待队列有数据才会返回,try_pop是立刻返回,没有数据时,返回false和空指针。
单线程测试

// 简单线程池.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include 
#include "tsafe_queue.h"

int main()
{
    tsafe_queue q;
    q.push(1);
    int i;
    q.try_pop(i);
    std::cout << i;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号