命令转发(准备用到异步变同步模式)

来源:互联网 发布:win8.1无法购买网络 编辑:程序博客网 时间:2024/05/01 09:12
#include "stdafx.h"#include <boost/function.hpp>#include <vector>#include <boost/bind.hpp>#include <boost/asio.hpp>#include <boost/thread.hpp>#include <conio.h>#include <boost/shared_ptr.hpp>#include <boost/make_shared.hpp>using namespace std;using namespace boost;class ICommand{public:virtual void Execute() = 0;virtual ~ICommand() { }};class DoCommand : public ICommand{private:int n_;public:DoCommand(int n) : n_(n) {//cout << "DoCommand()" << endl;}void Execute(){cout << "DoCommand::Execute() n = " << n_ << endl;}~DoCommand(){cout << "~DoCommand " << n_ << endl;}};class AllocCommand : public ICommand{private:intm_MemorySize;int*m_pMemory;public:AllocCommand(int memorySize) : m_MemorySize(memorySize), m_pMemory(new int[m_MemorySize]){//cout << "AllocCommand " << m_MemorySize << "bytes, address = " << m_pMemory << endl;}~AllocCommand(){cout << "~AllocCommand " << m_MemorySize << endl;delete[] m_pMemory;m_pMemory = NULL;m_MemorySize = 0;}void Execute(){cout << "AllocMemory::Execute() n = " << m_MemorySize << endl;}};void StopService(boost::asio::io_service& ios){while(1){if(_kbhit()){ios.stop();break;}}}void RunIoService(boost::asio::io_service& ios){while(1){try{ios.run();break;}catch(...){}}}typedef function<void ()> FCommand;typedef boost::shared_ptr<FCommand> CommandPtr;void HandleEvent(CommandPtr pCommand){(*pCommand)();}void main(){boost::shared_ptr<AllocCommand> pAlloc;boost::shared_ptr<DoCommand> pDo;std::vector<CommandPtr> cmdArray;std::vector<boost::weak_ptr<FCommand> > weakArray;cmdArray.reserve(100);for (int i = 1; i <= 10; ++i){CommandPtr pCmd;boost::weak_ptr<FCommand> weak;if (i % 2){pAlloc = boost::make_shared<AllocCommand>(i);pCmd.reset(new FCommand(bind(&ICommand::Execute, pAlloc)));}else{pDo = boost::make_shared<DoCommand>(i);pCmd.reset(new FCommand(bind(&ICommand::Execute, pDo)));}weak = pCmd;weakArray.push_back(weak);cmdArray.push_back(pCmd);}boost::asio::io_service ioservice;boost::asio::io_service::work work(ioservice);boost::asio::io_service::strand strand(ioservice);boost::thread t(&RunIoService, boost::ref(ioservice));boost::thread s(&StopService, boost::ref(ioservice));for (int i = 0; i < cmdArray.size(); ++i){strand.post(boost::bind(&HandleEvent, cmdArray[i]));}cmdArray.clear();t.join();}

原创粉丝点击