example_removal.c (1520B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/time.h> 4 5 #include "src/scheduler.h" 6 7 typedef struct { 8 int64_t start; 9 int ticks; 10 int removed; 11 } ChildCtx; 12 13 typedef struct { 14 int64_t start; 15 int64_t max_age_ms; 16 ChildCtx *child_ctx; 17 int ticks; 18 } ParentCtx; 19 20 static int child_task(int64_t ts, pt_task_t *task) { 21 ChildCtx *ctx = task->udata; 22 if (ctx->removed) { 23 free(ctx); 24 return SCHED_DONE; 25 } 26 ctx->ticks++; 27 printf(" [child] tick %d (age: %lld ms)\n", ctx->ticks, (long long)(ts - ctx->start)); 28 return SCHED_RUNNING; 29 } 30 31 static int parent_task(int64_t ts, pt_task_t *task) { 32 ParentCtx *ctx = task->udata; 33 ctx->ticks++; 34 int64_t age = ts - ctx->start; 35 printf("[parent] tick %d (elapsed: %lld ms)\n", ctx->ticks, (long long)age); 36 37 if (age >= ctx->max_age_ms) { 38 printf("[parent] child is old enough, signaling it to stop.\n"); 39 ctx->child_ctx->removed = 1; 40 free(ctx); 41 return SCHED_DONE; 42 } 43 44 return SCHED_RUNNING; 45 } 46 47 int main(void) { 48 struct timeval now; 49 gettimeofday(&now, NULL); 50 int64_t ts = (int64_t)now.tv_sec * 1000 + now.tv_usec / 1000; 51 52 ChildCtx *child_ctx = calloc(1, sizeof(ChildCtx)); 53 child_ctx->start = ts; 54 55 ParentCtx *parent_ctx = calloc(1, sizeof(ParentCtx)); 56 parent_ctx->start = ts; 57 parent_ctx->max_age_ms = 2500; 58 parent_ctx->child_ctx = child_ctx; 59 60 sched_create(child_task, child_ctx); 61 sched_create(parent_task, parent_ctx); 62 sched_main(); 63 64 printf("Both tasks are gone. Goodbye.\n"); 65 return 0; 66 }