我正在尝试使用“ thread_pool”增强功能来创建计时器。
我已经找到了如何使用带有“ io_service”的“ thread_group”来执行此操作的示例,但是我不理解如何将带有“ thread_pool”的“ boost :: asio :: high_resolution_timer”一起使用。
下面的代码,我可以使用“ io_service”和“ thread_group”创建线程池:
'application event handler
Set myEventHandler.appevent = Application
我的计时器如下:
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost;
using namespace boost::asio;
class IoServiceThreadPool :
public boost::enable_shared_from_this <IoServiceThreadPool>{
int pool_size;
int stack_size;
boost::shared_ptr<io_service> service;
boost::thread_group threads;
boost::scoped_ptr<io_service::work> work;
public:
IoServiceThreadPool(unsigned int pool_size_, unsigned int stack_size_) :
pool_size(pool_size_),
stack_size(stack_size_),
service(new io_service(pool_size_)),
threads(),
work()
{
}
void init()
{
thread_attributes attributes;
attributes.set_stack_size(stack_size);
work.reset(new io_service::work(*service.get()));
for (unsigned int i = 0; i < pool_size; i++)
{
threads.add_thread(
new boost::thread(
attributes,
boost::bind(&IoServiceThreadPool::run, shared_from_this())));
}
}
void run()
{
bool mustContinue(true);
do {
try {
boost::system::error_code ec;
service->run(ec);
mustContinue = false;
break;
}
catch (...) {
mustContinue = true;
}
} while (mustContinue);
}
boost::shared_ptr<io_service> getIoService()
{
return service;
}
};
要在2秒内触发我的计时器:
class MyTimer :
public boost::enable_shared_from_this<MyTimer> {
boost::asio::high_resolution_timer timer;
std::chrono::milliseconds interval;
public:
MyTimer(io_service & service_, unsigned long interval_) :
timer(service_),
interval(interval_)
{
timer.expires_at(
boost::asio::high_resolution_timer::clock_type::now());
}
void start()
{
timer.expires_at(
boost::asio::high_resolution_timer::clock_type::now()
+ interval);
timer.async_wait(boost::bind(
&MyTimer::timeoutCallback,
shared_from_this(),
boost::asio::placeholders::error));
}
void timeoutCallback(const boost::system::error_code& error)
{
cout << "Timer called!" << endl;
}
};
但是我想使用带有以下代码的“ boost :: asio :: thread_pool”:
boost::shared_ptr<IoServiceThreadPool> ioService(
boost::make_shared<IoServiceThreadPool>(4, 256 * 1024)
);
ioService->init();
boost::shared_ptr<MyTimer> timer(
boost::make_shared<MyTimer>(*(ioService->getIoService()), 2000)
);
timer->start();
有可能吗?