Advertisement
moldovexc

threeFibers

May 28th, 2023
1,198
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 1 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_func1,uctx_func2, uctx_func3, uctx_main;
  8.  
  9. void firstFiber(){
  10.     printf("Fiber1: started\n");
  11.     printf("Fiber1: Now swap context to fiber2\n");
  12.     swapcontext(&uctx_func1, &uctx_func2);
  13.     printf("Fiber1: returned\n");
  14.     printf("Fiber1: Now swap context to fiber2 again\n");
  15.     swapcontext(&uctx_func1, &uctx_func2);
  16. }
  17. void secondFiber(){
  18.     printf("Fiber2: started\n");
  19.     printf("Fiber2: Now swap context to fiber3\n");
  20.     swapcontext(&uctx_func2, &uctx_func3);
  21.     printf("Fiber2: returned\n");
  22.     printf("Fiber2: Now swap context to fiber3 again\n");
  23.     swapcontext(&uctx_func2, &uctx_func3);
  24.  
  25. }
  26. void thirdFiber(){
  27.     printf("Fiber3: started\n");
  28.     printf("Fiber3: Now swap context to fiber1\n");
  29.     swapcontext(&uctx_func3, &uctx_func1);
  30.     printf("Fiber3: returned\n");
  31.     printf("Fiber3: Now swap context to fiber1 again\n");
  32.     swapcontext(&uctx_func3, &uctx_main);
  33. }
  34.  
  35. int main(){
  36.     getcontext(&uctx_func1);
  37.     uctx_func1.uc_link = NULL;
  38.     uctx_func1.uc_stack.ss_sp = malloc(FIBER_STACK);
  39.     uctx_func1.uc_stack.ss_size = FIBER_STACK;
  40.     uctx_func1.uc_stack.ss_flags = 0;
  41.     makecontext(&uctx_func1, firstFiber, 0);
  42.    
  43.     getcontext(&uctx_func2);
  44.     uctx_func2.uc_link = NULL;
  45.     uctx_func2.uc_stack.ss_sp = malloc(FIBER_STACK);
  46.     uctx_func2.uc_stack.ss_size = FIBER_STACK;
  47.     uctx_func2.uc_stack.ss_flags = 0;
  48.     makecontext(&uctx_func2, secondFiber, 0);
  49.    
  50.     getcontext(&uctx_func3);
  51.     uctx_func3.uc_link = NULL;
  52.     uctx_func3.uc_stack.ss_sp = malloc(FIBER_STACK);
  53.     uctx_func3.uc_stack.ss_size = FIBER_STACK;
  54.     uctx_func3.uc_stack.ss_flags = 0;
  55.     makecontext(&uctx_func3, thirdFiber, 0);
  56.    
  57.  
  58.     printf("Main: swap context to fiber1\n");
  59.     swapcontext(&uctx_main, &uctx_func1);
  60.    
  61.    
  62.  
  63.  
  64.     printf("Main: returned\n");
  65.     printf("Main: exiting\n");
  66.  
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement