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

[c++多线程]

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

[c++多线程]

线程安全队列

#pragma once
//->from https://blog.csdn.net/what951006/article/details/77916490
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

template 
class ThreadSafe_Queue
{
private:
	mutable mutex m_mut;
	queue m_queue;
	condition_variable m_data_cond;
public:
	ThreadSafe_Queue() {}
	ThreadSafe_Queue(const ThreadSafe_Queue&) = delete;
	void push(T data)
	{
		lock_guard lg(m_mut);
		m_queue.push(data);
		m_data_cond.notify_one();
	}
	void WaitPop(T&t)
	{
		unique_lock ul(m_mut);
		m_data_cond.wait(ul, [this] {return !m_queue.empty(); });
		t = m_queue.front();
		m_queue.pop();
	}
	shared_ptr WaitPop()
	{
		unique_lock ul(m_mut);
		m_data_cond.wait(ul, [this] {return !m_queue.empty(); });

		shared_ptr res(make_shared(m_queue.front()));
		m_queue.pop();
		return res;
	}
	bool TryPop(T &t)
	{
		lock_guard lg(m_mut);
		if (m_queue.empty())
			return false;

		t = m_queue.front();
		m_queue.pop();
		return true;
	}

	shared_ptr TryPop()
	{
		lock_guard lg(m_mut);
		if (m_queue.empty())
			return shared_ptr();
		shared_ptr res(make_shared(m_queue.front()));
		m_queue.pop();
		return res;
	}

	bool IsEmpty()
	{
		lock_guard lg(m_mut);
		return m_queue.empty();
	}

};

线程主函数代码

#include "threadSafeQueue.h"

using namespace std;

ThreadSafe_Queue g_queue;
int g_index = 10;
void thread_Fuc() {
	cout << "thread_fuc1 startn";
	while (true) {
		int value = 0;
		g_queue.WaitPop(value);
		printf("wait_and_pop done! value=%d  thread id:%dn", value, std::this_thread::get_id());
	}
}

void thread_Fuc2() {
	cout << "thread_fuc2 startn";
	while (true) {

		std::this_thread::sleep_for(std::chrono::milliseconds(500)); //500 ms
		g_index++;
		g_queue.push(g_index);
	}
}

int main() {
	thread thd(thread_Fuc);
	thd.detach();

	thread thd2(thread_Fuc2);
	thd2.detach();

	int a;
	while (cin >> a) { ; }
	return 0;
}

运行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/384925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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