single ioservice multiple thread Model

来源:互联网 发布:涉案账户资金网络查控 编辑:程序博客网 时间:2024/05/22 16:01
#include "boost/asio.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include "boost/shared_ptr.hpp"
#include "boost/thread.hpp"
#include <iostream>
#include <vector>
#include <thread>


using namespace std;
using namespace boost::asio;


class  ASYNCIOS
{
public:
ASYNCIOS()
:ptrIosService_(new boost::asio::io_service)
,work(new boost::asio::io_service::work(*ptrIosService_))
,ptrDLTimber_(new boost::asio::deadline_timer(*ptrIosService_,
boost::posix_time::seconds(1)))
{}
void startworking(int seconds)
{
seconds_ = seconds;
ptrDLTimber_->expires_from_now(boost::posix_time::seconds(seconds_));
ptrDLTimber_->async_wait(boost::bind(&ASYNCIOS::async_wait,this)); 
for( int i = 0; i< 10; i++)
{
boost::shared_ptr<boost::thread> ptrThread
(new boost::thread(
boost::bind(&boost::asio::io_service::run,ptrIosService_) ));
threads_.push_back(ptrThread);
}
// ptrThread_.reset(new boost::thread(
// boost::bind(&boost::asio::io_service::run,ptrIosService_) ));
// ptrThread_->start_thread();
for( int i = 0; i< 10; i++)
threads_[i]->join();


}
void async_wait()
{
cout << "hello world!" <<  this_thread::get_id()<<endl;
ptrDLTimber_->expires_from_now(boost::posix_time::seconds(seconds_));
ptrDLTimber_->async_wait(boost::bind(&ASYNCIOS::async_wait,this));
}
protected:
private:
typedef boost::shared_ptr<boost::asio::io_service::work> workptr;
boost::shared_ptr<boost::asio::io_service> ptrIosService_;
//boost::shared_ptr<boost::thread> ptrThread_;
boost::shared_ptr<boost::asio::deadline_timer> ptrDLTimber_;
std::vector<boost::shared_ptr<boost::thread> > threads_;
int seconds_;
workptr work;
};


int main()
{
ASYNCIOS ios;
ios.startworking(1); //great it's working!
return 0;
}
0 0
原创粉丝点击