简而言之:
调用spawn ()时,Boost.Asio将执行一些配置任务,并使用strand到dispatch )的内部处理程序。 这个处理程序使用用户提供的函数作为入口点来创建协作程序。 在某些情况下,对spawn ) )的调用会调用内部处理程序并将其发布到io_serviving
如果操作完成,调用完成处理程序,io_service被放弃,或者Boost.Asio检测到协作已中断且无法恢复,Boost.Asio将破坏协作程序。
如上所述,在调用spawn ()后,使用strand调度使用用户提供的函数作为入口点来创建协作程序的内部处理程序。 将yield_context对象作为处理程序传递给异步操作时,将在使用该处理程序启动异步操作后立即生成Boost.Asio。 这个处理程序复制结果并重新开始协和式计算机。 上述链条为coroutine所有,用于保证恢复前产生的产量。 请考虑一个简单的例子,demonstrating spawn (
#包含
#包含
#包含
boost : asio : io _ service io _ service;
void other_work (
{
STD : cout ' other work ' STD :3360 endl;
}
void my _ work (boost : asio 3360: yield _ context yield _ context ) ) ) ) ) ) ) ) ) ) )。)
{
//Add more work to the io_service。
io_service.post(other_work );
//waitonatimerwithinthecoroutine。
boost : asio : deadline _ timer timer (io _ service );
timer.expires _ from _ now (boost :3360 POSIX _ time 33603360 seconds (1);
STD : cout ' start wait ' STD :3360 endl;
timer.async_wait(yield_context;
STD : cout ' woke up ' STD :3360 endl;
}
int main () )
{
boost :3360 asio : spawn (io _ service,my_work );
io_service.run (;
}
上述输出示例:
开始等待
Other work
Woke up
这试图说明示例的执行。 路径|表示活动堆栈,表示挂起的堆栈,箭头表示控制转移。
boost : asio : io _ service io _ service;
boost :3360 asio : spawn (io _ service,my_work );
`-- dispatch a coroutine creator
into the io_service。
io_service.run (;
|-- invoke the coroutine creator
| handler
| |-- create and jump into
| | into coroutine ---- my_work (
33660:|--postother _ work onto
: | the io_service
:|- -创建时间
33660:|- -设置表达式
:|--cout ' start wait ' endl;
33603360|--timer.async _ wait (yield ) ) ) )。
3360:|--create error _ codeonstack
3360:|--- initiate async _ wait operation,|| passingincompletionhandlerthat
33603360|||willresumethecoroutine
| `--返回
|-- io _ servicehaswork (the :
| other_work and async_wait ) :
|--invokeother_work(:
| `-- cout 'Other work' :
| endl;
|-- io _ servicestillhaswork 3360:
|(theAsync_waitoperation ) :
| . asyncwaitcompletes .
|-- invokecompletionhandler 3360:
| |-- copies error_code :
| |预配服务:
| | into the one on the :
| | coroutine stack :
|---resume---| `-return error code
: |-- cout 'Woke up.' endl;
:3360|--exiting my _ work block,timer is
:
| `--返回
`-- no outstanding work in
io_service,return。