single ioservice multiple thread Model

本文介绍如何利用Boost库中的并发和异步IO功能实现高效的数据处理任务,通过创建工作线程池和使用DeadlineTimer进行定时操作,演示了如何在C++中进行并发编程,特别适用于需要频繁I/O操作的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值