#include "itc.h" #include "utils.h" #include #include #include struct itc { int nslots; void **slots; int inputidx; int outputidx; sem_t emptied; sem_t occupied; }; itc *itc_alloc(int nslots) { itc *ctx; if (nslots <= 0) { return NULL; } ctx = calloc(1, sizeof(*ctx)); ctx->nslots = nslots; ctx->slots = (void **)calloc(nslots, sizeof(*ctx->slots)); sem_init(&ctx->emptied, 0, nslots); sem_init(&ctx->occupied, 0, 0); return ctx; } void itc_free(itc **ctx, itc_free_element free_element) { if (ctx == NULL || *ctx == NULL) { return; } itc_discard_all(*ctx, free_element); sem_destroy(&(*ctx)->emptied); sem_destroy(&(*ctx)->occupied); free((void *)(*ctx)->slots); free(*ctx); *ctx = NULL; } void *itc_retrieve(itc *ctx, int timeout_ms) { struct timespec ts; void *element; if (ctx == NULL) { return NULL; } timespec_add_ms(get_timespec(&ts), timeout_ms); if (sem_timedwait(&ctx->occupied, &ts)) { return NULL; } element = ctx->slots[ctx->outputidx]; ctx->outputidx = (ctx->outputidx + 1) % ctx->nslots; sem_post(&ctx->emptied); return element; } int itc_inject(itc *ctx, int timeout_ms, void *element) { struct timespec ts; if (ctx == NULL || element == NULL) { return -1; } timespec_add_ms(get_timespec(&ts), timeout_ms); if (sem_timedwait(&ctx->emptied, &ts)) { return -1; } ctx->slots[ctx->inputidx] = element; ctx->inputidx = (ctx->inputidx + 1) % ctx->nslots; sem_post(&ctx->occupied); return 0; } void itc_wait_empty(itc *ctx) { int i; if (ctx == NULL) { return; } for (i = 0; i < ctx->nslots; i++) { sem_wait(&ctx->emptied); } for (i = 0; i < ctx->nslots; i++) { sem_post(&ctx->emptied); } } void itc_discard_all(itc *ctx, itc_free_element free_element) { void *element; if (ctx == NULL) { return; } while ((element = itc_retrieve(ctx, 0)) != NULL) { if (free_element != NULL) { free_element(element); } } } int itc_get_queued(itc *ctx) { int val; if (ctx == NULL) { return -1; } sem_getvalue(&ctx->occupied, &val); return val; } int itc_get_slots(itc *ctx) { if (ctx == NULL) { return -1; } return ctx->nslots; }