发一个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;

}
 
代码可随意修改,转帖请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值