boost无锁队列queue
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,另外一个线程从队列读数据,看读出来的数据是否会混乱;
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.运行,测试结果。注意,全程没有使用一把锁,想写就写,想读就读,没有数据错乱的问题,就这么神奇!
posted on 2017-10-12 21:27 zhuxian2009 阅读(617) 评论(0) 编辑 收藏 举报