Advertisement
moldovexc

fibers

May 28th, 2023
934
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <ucontext.h>
  2. #include <malloc.h>
  3. #include <stdio.h>
  4.  
  5. #define FIBER_STACK 1024*64
  6.  
  7. ucontext_t uctx_func, uctx_main;
  8.  
  9. void fiber(){
  10.     printf("Fiber: started\n");
  11.     printf("Fiber: Now swap context to main\n");
  12.     swapcontext(&uctx_func, &uctx_main);
  13.     printf("Fiber: returned\n");
  14.     printf("Fiber: Now swap context to main again\n");
  15.     swapcontext(&uctx_func, &uctx_main);
  16. }
  17.  
  18. int main(){
  19.     getcontext(&uctx_func);
  20.     uctx_func.uc_link = NULL;
  21.     uctx_func.uc_stack.ss_sp = malloc(FIBER_STACK);
  22.     uctx_func.uc_stack.ss_size = FIBER_STACK;
  23.     uctx_func.uc_stack.ss_flags = 0;
  24.     makecontext(&uctx_func, fiber, 0);
  25.  
  26.     printf("Main: swap context to fiber\n");
  27.     swapcontext(&uctx_main, &uctx_func);
  28.  
  29.     printf("Main: returned\n");
  30.  
  31.     printf("Main: swap context to fiber again\n");
  32.     swapcontext(&uctx_main, &uctx_func);
  33.  
  34.     printf("Main: returned\n");
  35.     printf("Main: exiting\n");
  36.  
  37.     return 0;
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement