简介
task_io_service运行在多线程情况时,call_stack来管理运行io_service的多个线程
结构
其中key为task_io_service,value为task_io_service_thread_info
初始化
是在task_io_service::run
中,创建task_io_service_thread_info的局部变量(循环没有退出时一直存在),同时添加到call_stack的栈顶
std::size_t task_io_service::run(boost::system::error_code& ec)
{
ec = boost::system::error_code();
if (outstanding_work_ == 0)
{
stop();
return 0;
}
thread_info this_thread;
this_thread.private_outstanding_work = 0;
thread_call_stack::context ctx(this, this_thread);
mutex::scoped_lock lock(mutex_);
std::size_t n = 0;
for (; do_run_one(lock, this_thread, ec); lock.lock())
if (n != (std::numeric_limits<std::size_t>::max)())
++n;
return n;
}
使用
在任务分发时,如果当前调用线程是io线程,则直接调用,否则放入对应的队列中
template <typename Handler>
void task_io_service::dispatch(Handler& handler)
{
if (thread_call_stack::contains(this))
{
fenced_block b(fenced_block::full);
boost_asio_handler_invoke_helpers::invoke(handler, handler);
}
else
{
// Allocate and construct an operation to wrap the handler.
typedef completion_handler<Handler> op;
typename op::ptr p = { boost::asio::detail::addressof(handler),
boost_asio_handler_alloc_helpers::allocate(
sizeof(op), handler), 0 };
p.p = new (p.v) op(handler);
BOOST_ASIO_HANDLER_CREATION((p.p, "io_service", this, "dispatch"));
do_dispatch(p.p);
p.v = p.p = 0;
}
}