boost无锁队列queue

本文展示了一个基于Boost库的高性能队列实现示例。通过使用Boost库中的lockfree队列,实现多线程环境下无需显式加锁的数据交换过程。示例包括了队列的创建、线程调度及数据的读写测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boost基本库包含很多实用的类库,比如队列,以下是高性能queue的简单例子


1.创建工程,然后设置头文件和lib库的路径,值得注意的是,Debug时必须选择“多线程调试(/MTD)”,Release时选择"多线程(/MT)";

2.包含头文件

#include <boost/lockfree/queue.hpp>
#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/mutex.hpp>

using namespace boost;
using namespace boost::threadpool;
using namespace boost::lockfree;


3.定义一个结构体tagMyStruct,和结构体队列que

typedef struct _MYSTRUCT_ 
{
	int nID;
	char GUID[64];
	_MYSTRUCT_()
	{
		memset(this,0x0,sizeof(_MYSTRUCT_));
	}
}tagMyStruct;


//指定使用固定大小的队列 
//boost::lockfree::fixed_sized<true>
//使用动态大小的队列 
//boost::lockfree::fixed_sized<false>
boost::lockfree::queue<tagMyStruct, fixed_sized<false> > que(0);

4.定义一个全局的递增变量g_nID;为了测试队列的性能,定义三个线程,其中两个线程写数据到队列que,另外一个线程从队列读数据,看读出来的数据是否会混乱;

注:i++,i--,++i,--i均不是原子操作,实际使用中,需要对g_nID改写的业务加锁。

int g_nID=0;
void Thread_SetQueue()
{
	bool bRet = false;

	//插入数据

	tagMyStruct tagIn;
	strcpy(tagIn.GUID,"1234556");

	while (1)
	{
		tagIn.nID = g_nID++;
		bRet = que.push(tagIn);
		boost::thread::sleep(boost::get_system_time()+boost::posix_time::millisec(1000));
	}
}

void Thread_SetQueue2()
{
	bool bRet = false;

	//插入数据

	tagMyStruct tagIn;
	strcpy(tagIn.GUID,"222222");

	while (1)
	{
		tagIn.nID = g_nID++;
		bRet = que.push(tagIn);
		boost::thread::sleep(boost::get_system_time()+boost::posix_time::millisec(500));
	}
}

void Thread_GetQueue()
{
	bool bRet = false;

	//取出数据
	tagMyStruct tagOut;

	while(1)
	{
		if(que.pop(tagOut))
		{
			printf("取出一个数:ID=%d  GUDI=%s\n",tagOut.nID,tagOut.GUID);
		}
		else
			boost::thread::sleep(boost::get_system_time()+boost::posix_time::millisec(200));;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{

	pool QueThread(3);	

	QueThread.schedule(&Thread_SetQueue);

	QueThread.schedule(&Thread_SetQueue2);

	QueThread.schedule(&Thread_GetQueue);
	
	QueThread.wait();
	return 0;
}

5.运行,测试结果。注意,全程没有使用一把锁,想写就写,想读就读,没有数据错乱的问题,就这么神奇!



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值