Advertisement
Guest User

psync.c

a guest
Oct 4th, 2018
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.25 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct psync_state {void *lbl; void *data;} psync_state;
  5.  
  6. #define CONCAT1(a, b) a ## b
  7. #define CONCAT2(a, b) CONCAT1(a, b)
  8.  
  9. #define PDECL(ret, name, ...) \
  10.     typedef ret name ## _ret; \
  11.     psync_state name(psync_state _psync_st, __VA_ARGS__)
  12.  
  13. #define _PSTRUCT(var)   typeof(var) var;
  14. #define _PASSIGN(var) var = _psync_args->var;
  15. #define _PCOMMA(var)  var,
  16.  
  17. #define _PSTVAR(_) _(_psync_call)
  18.  
  19. #define PINIT() \
  20.     psync_state _psync_call; \
  21.     struct _pstruct {PVARS(_PSTRUCT) _PSTVAR(_PSTRUCT)} *_psync_args; \
  22.     if(!_psync_st.lbl){ \
  23.         _psync_args = malloc(sizeof(struct _pstruct)); \
  24.     }else{ \
  25.         _psync_args = _psync_st.data; \
  26.         PVARS(_PASSIGN) \
  27.         _PSTVAR(_PASSIGN) \
  28.         goto *_psync_st.lbl; \
  29.     }
  30.  
  31. #define PWAIT(lbl) \
  32.     *_psync_args = (struct _pstruct){PVARS(_PCOMMA) _PSTVAR(_PCOMMA)}; \
  33.     return (psync_state){&&lbl, _psync_args}; \
  34.     lbl:
  35.  
  36. #define PCALL(func, ...) ({ \
  37.         _psync_call = (psync_state){0}; \
  38.         _psync_call = func(_psync_call, __VA_ARGS__); \
  39.         while(_psync_call.lbl){ \
  40.             PWAIT(CONCAT2(func, CONCAT2(_call_, __COUNTER__))); \
  41.             _psync_call= func(_psync_call, __VA_ARGS__); \
  42.         } \
  43.         *(func ## _ret*)_psync_call.data; \
  44.     })
  45.  
  46. #define PRET(var) \
  47.     *(typeof(var)*)_psync_args = var; \
  48.     return (psync_state){0, _psync_args};
  49.  
  50. PDECL(int, add, int, int);
  51.  
  52. PDECL(int, add, int a, int b) {
  53.     int c;
  54. #define PVARS(_) _(a) _(b) _(c)
  55.     PINIT()
  56.     c = 0;
  57.     c += a;
  58.     PWAIT(add_b)
  59.     c += b;
  60.     PRET(c)
  61. #undef PVARS
  62. }
  63.  
  64. PDECL(int, add3, int a, int b, int c){
  65.     int d;
  66. #define PVARS(_) _(a) _(b) _(c) _(d)
  67.     PINIT()
  68.     d = 0;
  69.     d = PCALL(add, d, a);
  70.     d = PCALL(add, d, b);
  71.     d = PCALL(add, d, c);
  72.     PRET(d);
  73. #undef PVARS
  74. }
  75.  
  76. int main(void){
  77.     struct psync_state st1, st2;
  78.     st1 = add3((psync_state){0}, 10, 25, 13);
  79.     st2 = add3((psync_state){0}, 100, -30, 25);
  80.     while(st1.lbl || st2.lbl){
  81.         if(st1.lbl) st1 = add3(st1, 0,0,0);
  82.         if(st2.lbl) st2 = add3(st2, 0,0,0);
  83.     }
  84.     printf("1: %d\n", *((add3_ret*)st1.data));
  85.     printf("2: %d\n", *((add3_ret*)st2.data));
  86.     free(st1.data);
  87.     free(st2.data);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement