c语言spawn函数什么作用,c – boost :: asio :: spawn有什么作用?

简而言之:

>当调用spawn()时,Boost.Asio执行一些设置工作,然后将使用strand到dispatch()内部处理程序,该处理程序使用用户提供的函数作为入口点创建协同程序.在某些条件下,可以在对spawn()的调用中调用内部处理程序,有时将其发布到io_service以进行延迟调用.

>协程暂停,直到操作完成并调用完成处理程序,io_service被销毁,或者Boost.Asio检测到协程已被挂起而无法恢复它,此时Boost.Asio将破坏协同程序.

如上所述,当调用spawn()时,然后使用strand来调度()内部处理程序,该处理程序使用用户提供的函数作为入口点创建协同程序.当yield_context对象作为处理程序传递给异步操作时,Boost.Asio将在使用完成处理程序启动异步操作后立即生成,该处理程序将复制结果并恢复协程.前面提到的链是由coroutine所有,用于保证在恢复之前产生的产量.让我们考虑一个简单的例子demonstrating spawn():

#include

#include

#include

boost::asio::io_service io_service;

void other_work()

{

std::cout << "Other work" << std::endl;

}

void my_work(boost::asio::yield_context yield_context)

{

// Add more work to the io_service.

io_service.post(&other_work);

// Wait on a timer within the coroutine.

boost::asio::deadline_timer timer(io_service);

timer.expires_from_now(boost::posix_time::seconds(1));

std::cout << "Start wait" << std::endl;

timer.async_wait(yield_context);

std::cout << "Woke up" << std::endl;

}

int main ()

{

boost::asio::spawn(io_service,&my_work);

io_service.run();

}

以上示例输出:

Start wait

Other work

Woke up

这是尝试说明示例的执行.路径|表示活动堆栈,:表示挂起的堆栈,箭头用于表示控制转移:

boost::asio::io_service io_service;

boost::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()

: : |-- post &other_work onto

: : | the io_service

: : |-- create timer

: : |-- set timer expiration

: : |-- cout << "Start wait" << endl;

: : |-- timer.async_wait(yield)

: : | |-- create error_code on stack

: : | |-- initiate async_wait operation,: : | | passing in completion handler that

: : | | will resume the coroutine

| `-- return

|-- io_service has work (the : :

| &other_work and async_wait) : :

|-- invoke other_work() : :

| `-- cout << "Other work" : :

| << endl; : :

|-- io_service still has work : :

| (the async_wait operation) : :

| ...async wait completes... : :

|-- invoke completion handler : :

| |-- copies error_code : :

| | provided by service : :

| | into the one on the : :

| | coroutine stack : :

| |-- resume ----> | `-- return error code

: : |-- cout << "Woke up." << endl;

: : |-- exiting my_work block,timer is

: : | destroyed.

| `-- return

`-- no outstanding work in

io_service,return.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值