| 1 | #include <stdio.h> |
| 2 | #include <stddef.h> |
| 3 | #include "coroutine.h" |
| 4 | #include "generator.h" |
| 5 | #include "asleep.h" |
| 6 | #include "task.h" |
| 7 | |
| 8 | #include <dirent.h> |
| 9 | #include <string.h> |
| 10 | #include <stdlib.h> |
| 11 | #include <time.h> |
| 12 | |
| 13 | #define DEMO_STACK_SIZE (8192*sizeof(void *)) |
| 14 | |
| 15 | void *chaindeeper(void *param){ |
| 16 | // enough headroom for printf on an Intel Mac - your system may be different |
| 17 | if (Coroutine_GetStackHeadroom() < 2000){ |
| 18 | void *result; |
| 19 | bool fail = Coroutine_Chain(DEMO_STACK_SIZE, 0, chaindeeper, param, &result); |
| 20 | return fail ? NULL : result; |
| 21 | } |
| 22 | printf("%ld %ld\n", (long)param, Coroutine_GetStackHeadroom()); |
| 23 | bool domore = Generator_Yield(param); |
| 24 | if (domore){ |
| 25 | long depth = (long)param; |
| 26 | if (depth > 1000){ |
| 27 | return NULL; |
| 28 | } |
| 29 | return chaindeeper((void *)(depth + 1)); |
| 30 | } |
| 31 | return NULL; |
| 32 | } |
| 33 | |
| 34 | |
| 35 | void *chaintest( |
| 36 | void *param |
| 37 | ){ |
| 38 | (void)param; |
| 39 | |
| 40 | // Need to run two coroutines so that at least one of their stacks is limited, and so |
| 41 | // needs to chain |
| 42 | Generator gen1; |
| 43 | Generator_ctor(&gen1, DEMO_STACK_SIZE, 0, chaindeeper, 0); |
| 44 | Generator gen2; |
| 45 | Generator_ctor(&gen2, DEMO_STACK_SIZE, 0, chaindeeper, 0); |
| 46 | void *param1; |
| 47 | void *param2; |
| 48 | while(Generator_Next(&gen1, ¶m1) && Generator_Next(&gen2, ¶m2)){ |
| 49 | } |
| 50 | Generator_dtor(&gen2); |
| 51 | Generator_dtor(&gen1); |
| 52 | |
| 53 | Coroutine_Report report = Coroutine_GetReport(); |
| 54 | printf("%d routines using a pool of %d, min headroom %zu\n", report.coroutines_created, report.coroutines_pool_size, report.lowest_headroom); |
| 55 | |
| 56 | return param; |
| 57 | } |
| 58 | |
| 59 | |
| 60 | int main(int argc, char *argv[]) { |
| 61 | (void)argc; |
| 62 | (void)argv; |
| 63 | |
| 64 | Coroutine_Run(DEMO_STACK_SIZE, 0, chaintest, NULL, NULL); |
| 65 | |
| 66 | return 0; |
| 67 | } |
| 68 | |