example_sem.c (1324B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 5 #include "src/sched-sem.h" 6 #include "src/scheduler.h" 7 8 typedef struct { 9 struct sched_sem sem; 10 int tokens_produced; 11 int tokens_consumed; 12 } ProducerCtx; 13 14 typedef struct { 15 struct sched_sem *sem; 16 int *tokens_consumed; 17 } ConsumerCtx; 18 19 static int producer(int64_t ts, pt_task_t *task) { 20 ProducerCtx *ctx = task->udata; 21 (void)ts; 22 23 sched_sem_signal(&ctx->sem, 1); 24 ctx->tokens_produced++; 25 26 if (ctx->tokens_produced >= 10) { 27 printf("Producer done (produced %d tokens)\n", ctx->tokens_produced); 28 return SCHED_DONE; 29 } 30 return SCHED_RUNNING; 31 } 32 33 static int consumer(int64_t ts, pt_task_t *task) { 34 ConsumerCtx *ctx = task->udata; 35 (void)ts; 36 37 sched_sem_wait(ctx->sem); 38 (*ctx->tokens_consumed)++; 39 40 if (*ctx->tokens_consumed >= 10) { 41 printf("Consumer done (consumed %d tokens)\n", *ctx->tokens_consumed); 42 return SCHED_DONE; 43 } 44 return SCHED_RUNNING; 45 } 46 47 int main(void) { 48 ProducerCtx producer_ctx = {.sem = {.value = 0}, .tokens_produced = 0}; 49 int tokens_consumed = 0; 50 ConsumerCtx consumer_ctx = {.sem = &producer_ctx.sem, .tokens_consumed = &tokens_consumed}; 51 52 sched_create(producer, &producer_ctx); 53 sched_create(consumer, &consumer_ctx); 54 sched_main(); 55 56 return 0; 57 }