Skip to content

Instantly share code, notes, and snippets.

@byyam
Created October 24, 2019 15:06
Show Gist options
  • Save byyam/bafb9d6ec97800a77c4b56eb6cfd5648 to your computer and use it in GitHub Desktop.
Save byyam/bafb9d6ec97800a77c4b56eb6cfd5648 to your computer and use it in GitHub Desktop.
coroutine cpp
#include <stdio.h>
#include <ucontext.h>
#include <list>
static void one();
static void two();
static void three();
static ucontext_t ctx1;
static ucontext_t ctx2;
static ucontext_t ctx3;
static char stack1[4096];
static char stack2[8192];
int main(int argc, char *argv[])
{
printf("main start...\n");
//create three() context
getcontext(&ctx1);
ctx1.uc_stack.ss_sp = stack1;
ctx1.uc_stack.ss_size = sizeof(stack1);
ctx1.uc_link = &ctx3;//ctx3 after ctx1.
makecontext(&ctx1, three, 0);
//create two() context
getcontext(&ctx2);
ctx2.uc_stack.ss_sp = stack2;
ctx2.uc_stack.ss_size = sizeof(stack2);
ctx2.uc_link = &ctx1;//ctx1 after ctx2.
makecontext(&ctx2, two, 0);
one();
printf("main end...\n");
return 0;
}
void one()
{
printf("%s start...\n", __func__);
//swift to ctx2, save current state in ctx3.
swapcontext(&ctx3, &ctx2);
printf("%s end...\n", __func__);
}
void two()
{
printf("%s\n", __func__);
}
void three()
{
printf("%s\n", __func__);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment