fibonacci-test.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* generate the fibonacci sequence using coroutines
  2. Copyright (C) 2018 Ariadne Devos
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <stdio.h>
  15. #include "../lco.h"
  16. static _Noreturn void
  17. produce_fibonacci(struct lco_coroutine *current);
  18. static _Noreturn void
  19. consume_fibonacci(struct lco_coroutine *current);
  20. static struct lco_coroutine print = {};
  21. static struct lco_coroutine fibonacci = {};
  22. static struct lco_position thread;
  23. static unsigned long c;
  24. void
  25. produce_fibonacci(struct lco_coroutine *current)
  26. {
  27. unsigned long a = 0, b = 1;
  28. for (int i = 0; i < 80; i++) {
  29. c = a + b;
  30. a = b;
  31. b = c;
  32. lco_continue(&print, current, 0);
  33. }
  34. lco_pause(current, &thread, 0);
  35. }
  36. void
  37. consume_fibonacci(struct lco_coroutine *current)
  38. {
  39. while (1) {
  40. fprintf(stdout, "%ld\n", c);
  41. lco_continue(&fibonacci, current, 0);
  42. }
  43. }
  44. #define STACKSIZE 16384
  45. _Alignas(LCO_STACK_ALIGNMENT)
  46. static char stack0[STACKSIZE];
  47. _Alignas(LCO_STACK_ALIGNMENT)
  48. static char stack1[STACKSIZE];
  49. _Alignas(LCO_STACK_ALIGNMENT)
  50. static char stack2[STACKSIZE];
  51. int
  52. main(int argc, char **argv)
  53. {
  54. /* XXX write a program to generate this*/
  55. print.entry = &consume_fibonacci;
  56. print.stack_size = STACKSIZE;
  57. print.stack_array = stack0;
  58. fibonacci.entry = &produce_fibonacci;
  59. fibonacci.stack_size = STACKSIZE;
  60. fibonacci.stack_array = stack1;
  61. lco_auto_sigaltstack(STACKSIZE, stack2);
  62. lco_init(&print);
  63. lco_init(&fibonacci);
  64. lco_resume(&fibonacci, &thread, 0);
  65. return 0;
  66. }