NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
```cpp #include <stdio.h> #include <ucontext.h> #include <unistd.h> #include <stdlib.h> #define CO_STACK_SIZE 1024 * 1024 void sub_coroutine() { puts("sub coroutine"); } int main() { ucontext_t ctx; ucontext_t main_ctx; void *co_stack = malloc(CO_STACK_SIZE); getcontext(&ctx); ctx.uc_stack.ss_sp = co_stack; ctx.uc_stack.ss_size = CO_STACK_SIZE; ctx.uc_link = &main_ctx; for (int i = 0; i < 2; i++) { // 创建子协程上下文 makecontext(&ctx, &sub_coroutine, 0); // 切换到子协程 swapcontext(&main_ctx, &ctx); } puts("main end"); free(co_stack); return 0; } ``` ``` evenleo@ubuntu:~/workspace/test$ g++ main.cpp evenleo@ubuntu:~/workspace/test$ ./a.out sub coroutine sub coroutine main end ```