用ACE实现生产者消费者模式

这个例子主要用到了ACE_TASK类和ACE_Thread_Manager类


#include "ace/Log_Msg.h"
#include "ace/Task.h"
#include "ace/OS.h"
#include "ace/Message_Block.h"
#include <stdio.h>
#include <string.h>

typedef struct User_
{
	int len;
	char buffer[20];
	int count;
} User;

//The Consumer Task.
class Consumer:
	public ACE_Task<ACE_MT_SYNCH>
{
public:
	int open(void*)
	{
		ACE_DEBUG((LM_DEBUG, "(%t) Consumer task opened /n"));
		//Activate the Task
		activate(THR_NEW_LWP,1);
		return 0;
	}
	//The Service Processing routine
	int svc(void)
	{
		//Get ready to receive message from Producer
		ACE_Message_Block * mb =0;
		int count = 0;
		do
		{
			mb=0;
			//Get message from underlying queue
			getq(mb);
			User *user = (User*)mb->rd_ptr();
			count = user->count;
			ACE_DEBUG((LM_DEBUG,
				"(%t)Got message: %s,%d,%d from remote task/n",user->buffer,user->len,user->count));
			delete user;	
			mb->release();
		}while(count < 10);
		return 0;
	}
	int close(u_long)
	{
		ACE_DEBUG((LM_DEBUG,"Consumer closes down /n"));
		return 0;
	}
};
class Producer : public ACE_Task<ACE_MT_SYNCH>
{
public:
	Producer(Consumer * consumer):consumer_(consumer), count(0)
	{
		//mb_=new ACE_Message_Block((char*)&data_,sizeof(data_));
	}
	int open(void*)
	{
		ACE_DEBUG((LM_DEBUG, "(%t) Producer task opened /n"));
		//Activate the Task
		activate(THR_NEW_LWP,1);
		return 0;
	}
	//The Service Processing routine
	int svc(void)
	{
		while(count<11)
		{
			//Send message to consumer
			ACE_DEBUG((LM_DEBUG,
				"(%t)Sending message: %d to remote task/n",count));
			User *user = new User();
			sprintf(user->buffer,"hello %d",count);
			user->len = strlen(user->buffer);
			user->count = count;
			mb_=new ACE_Message_Block((char*)user,sizeof(User));
			consumer_->putq(mb_);
			//Go to sleep for a sec.
			ACE_OS::sleep(1);
			count++;
		}
		return 0;
	}
	int close(u_long)
	{
		ACE_DEBUG((LM_DEBUG,"Producer closes down /n"));
		return 0;
	}
private:
	int count;
	Consumer * consumer_;
	ACE_Message_Block * mb_;
};
int main(int argc, char * argv[])
{
	Consumer * consumer = new Consumer;
	Producer * producer = new Producer(consumer);
	producer->open(0);
	consumer->open(0);
	//Wait for all the tasks to exit.
	ACE_Thread_Manager::instance()->wait();
	ACE_OS::system("pause");
	delete producer;
	delete consumer;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值