发一个C++写的跨平台的BlockingQueue

BlockingQueue大家都不陌生吧,它简化了多线程的开发,常用于生产者-消费者模式。可惜只有java这些高级语言才提供。我参考了网上的跨平台线程类,写了个跨平台的BlockingQueue,希望对大家有帮助。

下载地址:http://download.csdn.net/source/2052785

使用方法:

Linux下请切换到目录,make即可。(Makefile还不太熟悉,凑合着能用就行)

Windows下请用VS2005以上版本打开sln文件即可。

bin目录下有编译好的测试实例

==============================================================

未提供打包成库文件的命令,有需要者可自行打包。

测试代码(WIN32版)

#include "NetWay/BlockingQueue.h"
#include <iostream>
#include <string>
#include <windows.h>


using namespace std;

NetWay::BlockingQueue<string> bq;

DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
	int* n = (int *)lpParam;
	printf("Thread %d is waiting/n",n);
	string str = bq.take();
	printf("Thread %d got an element:%s /n",n,str.c_str());

	return 0;
}

void main()
{	
	DWORD dlen;
	for(int i = 0; i < 5; i++)
	{
		CreateThread(NULL,0,ThreadFunc,(LPVOID)i,0,&dlen);
	}

	Sleep(2*1000);  // all threads are waiting.
	
	bq.enqueue("1");
	bq.enqueue("2");
	bq.enqueue("3");

	Sleep(3*1000); // still 2 threads are waiting.

	bq.enqueue("4");

	Sleep(2*1000); // only 1 thread is waiting

	printf("now the main thread is trying to poll an element/n");

	try 
	{
		bq.poll(3*1000);
	}catch(...)
	{
		printf("poll time out.");
	}

	cin>>dlen;

}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章