/** * 这个结构体用于保存协程执行过程中的上下文,包括栈变量,参数等 */ struct__funFrame { void (*resume_fn)(__funFrame *); void (*destroy_fn)(__funFrame *); std::__coroutine_traits_sfinae<generator>::promise_type __promise; int __suspend_index; bool __initial_await_suspend_called; std::suspend_always __suspend_62_11; std::suspend_always __suspend_66_5; std::suspend_always __suspend_62_11_1; }; /** * 注意展开后的fun中并没有原先的代码逻辑,而是创造了一个generator结构体,并且和执行真正逻辑的__funResume关联在一起 **/ generator fun() { /* Allocate the frame including the promise */ /* Note: The actual parameter new is __builtin_coro_size */ __funFrame * __f = reinterpret_cast<__funFrame *>(operatornew(sizeof(__funFrame))); __f->__suspend_index = 0; __f->__initial_await_suspend_called = false; /* Construct the promise. */ new (&__f->__promise)std::__coroutine_traits_sfinae<generator>::promise_type{}; /* Forward declare the resume and destroy function. */ void __funResume(__funFrame * __f); void __funDestroy(__funFrame * __f); /* Assign the resume and destroy function pointers. */ __f->resume_fn = &__funResume; __f->destroy_fn = &__funDestroy; /* Call the made up function with the coroutine body for initial suspend. This function will be called subsequently by coroutine_handle<>::resume() which calls __builtin_coro_resume(__handle_) */ __funResume(__f); return __f->__promise.get_return_object(); }
/* This function invoked by coroutine_handle<>::resume() */ void __funResume(__funFrame * __f) { try { /* Create a switch to get to the correct resume point */ switch(__f->__suspend_index) { case0: break; case1: goto __resume_fun_1; case2: goto __resume_fun_2; } // 省略一堆代码 __resume_fun_1: // 省略一堆代码 // 主要执行逻辑 printf("Hello,"); co_yield 4; __resume_fun_2: // 省略一堆代码 printf("Wrold.\n"); co_return 2; } catch(...) { // ... } __final_suspend: // 省略一堆代码 ; }
auto handler2 = [](int a) -> generator { for (int i = 1; i <= 5; ++i) { std::cout << i << " " << a << std::endl; co_yield i; } }; auto g3 = getTask(std::move(handler2), 1);