Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. //
  2. // main.c
  3. // async_test
  4. //
  5. // Created by Rory B. Bellows on 15/10/2017.
  6. // Copyright © 2017 Rory B. Bellows. All rights reserved.
  7. //
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <stdbool.h>
  12. #include <setjmp.h>
  13. #include <time.h>
  14.  
  15. // int max_iteration, iter;
  16. //
  17. // jmp_buf Main, PointA, PointB;
  18. //
  19. // void Ping(void);
  20. // void Pong(void);
  21. //
  22. // void main(int argc, char* argv[])
  23. // {
  24. // max_iteration = abs(atoi(argv[1]));
  25. // iter = 1;
  26. // if (setjmp(Main) == 0)
  27. // Ping();
  28. // if (setjmp(Main) == 0)
  29. // Pong();
  30. // longjmp(PointA, 1);
  31. // }
  32. //
  33. // void Ping(void)
  34. // {
  35. // if (setjmp(PointA) == 0)
  36. // longjmp(Main, 1);
  37. // while (1) {
  38. // printf("%3d : Ping-", iter);
  39. // if (setjmp(PointA) == 0)
  40. // longjmp(PointB, 1);
  41. // }
  42. // }
  43. //
  44. // void Pong(void)
  45. // {
  46. // if (setjmp(PointB) == 0)
  47. // longjmp(Main, 1);
  48. // while (1) {
  49. // printf("Pong\n");
  50. // iter++;
  51. // if (iter > max_iteration)
  52. // exit(0);
  53. // if (setjmp(PointB) == 0)
  54. // longjmp(PointA, 1);
  55. // }
  56. // }
  57.  
  58. typedef struct {
  59. jmp_buf main;
  60. int length;
  61. jmp_buf* jmps;
  62. } async_ctx;
  63.  
  64. int __async_ctx_resize(async_ctx* ctx, int size) {
  65. if (!ctx)
  66. return -1;
  67.  
  68. jmp_buf* new = realloc(ctx->jmps, size * sizeof(void*));
  69. if (!new)
  70. return -1;
  71. ctx->jmps = new;
  72.  
  73. return 1;
  74. }
  75.  
  76. #define async(fn) ({ \
  77. if (setjmp(ctx.main) == 0) \
  78. fn; \
  79. })
  80.  
  81. #define coroutine(fn, ...) __attribute__((noinline)) fn { \
  82. async_ctx ctx; \
  83. ctx.length = 0; \
  84. ctx.jmps = malloc(sizeof(jmp_buf)); \
  85. if (!ctx.jmps) { \
  86. puts("FATAL: malloc() failed."); \
  87. exit(EXIT_FAILURE); \
  88. } \
  89. __VA_ARGS__ \
  90. free(ctx.jmps); \
  91. }
  92.  
  93. coroutine(int main(int argc, const char* argv[]), {
  94. return 0;
  95. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement