【发布时间】:2017-04-19 16:28:06
【问题描述】:
我已经集成了Boost的asio服务,并结合线程池使用。
创建了一个同时处理期货和异步任务的线程池后,我想进一步扩展它以处理截止时间计时器(反模式?)。不幸的是,我在处理模板化代码方面达到了我的极限。更准确地说,我想传递一个 boost::posix_time (例如: boost::posix_time::milliseconds(100) 或 boost::posix_time::seconds(5) ),但我很难理解我怎么能让这成为可能。
下面的部分代码是我的线程池的当前实现。
//////////////////////////////////////////////////////////////////////////
class thread_pool
{
public:
// ...
// Other boring stuff here...
//////////////////////////////////////////////////////////////////////////
template<class Task>
void enqueue_async(Task task)
{
m_pIO->post( std::bind(&thread_pool::wrap_task, this,
std::function< void() >( task )));
}
//////////////////////////////////////////////////////////////////////////
// NOTE: Needing help here - 'expiry_time' should be relative.
template <class Task, class ???>
void enqueue_deadline_async(Task task, const ??? & expiry_time)
{
const std::shared_ptr<boost::asio::basic_deadline_timer<???> > apTimer = std::make_shared<boost::asio::deadline_timer>(*get_service_pointer(), expiry_time);
apTimer->async_wait(std::bind(&thread_pool::enqueue_async, this, task));
}
private:
//////////////////////////////////////////////////////////////////////////
void wrap_task( std::function< void() > task )
{
try
{
task();
}
catch (const std::exception &e)
{
// Todo: Log that there is a problem!!
BOOST_ASSERT_MSG(0,e.what());
}
}
};
到目前为止,我一直在使用 enqueue_task(...) 将异步任务排队以供线程池处理。我现在想扩展线程池,以便能够异步调用回调参数到截止时间计时器(请参阅 enqueue_deadline_async())但让线程池处理任务。
将thread_pool与deadline_time集成的原因是:
- 尽量减少代码中同时运行的 io_service 数量。
- 防止deadline_time 阻塞io_service 太久 - 减少对其他挂起计时器的影响。
最后,我在 io_service 中的嵌套调用是否危险?
环境配置:
- Ubuntu v17.04 (Zesty) x86_x64
- Boost v1.63
- GCC 6.3
【问题讨论】:
标签: c++ boost-asio