iiotfeeder/queue.c
Wolfgang Hottgenroth a99c3b7121
queue and so on
2021-10-17 14:41:21 +02:00

48 lines
1.3 KiB
C

#include <queue.h>
#include <stdlib.h>
#include <logging.h>
#include <pthread.h>
t_queue *initQueue() {
t_queue *queue = (t_queue*) malloc(sizeof(t_queue));
if (! queue) {
logmsg(LOG_ERR, "out of memory when initializing queue");
return NULL;
}
queue->root = (t_queueBlock*) malloc(sizeof(t_queueBlock));
if (! queue->root) {
logmsg(LOG_ERR, "out of memory when initializing root of queue");
free(queue);
queue = NULL;
return NULL;
}
queue->head = queue->root;
queue->head_lock = PTHREAD_MUTEX_INITIALIZER;
queue->tail = queue->root;
queue->tail_lock = PTHREAD_MUTEX_INITIALIZER;
queue->notEmptyLock = PTHREAD_MUTEX_INITIALIZER;
queue->notEmpty = PTHREAD_COND_INITIALIZER;
}
// allocate memory for the queueBlock on your own and fill in the payloadc
void putQueue(t_queue *queue, t_queueBlock *queueBlock);
// will block if queue is empty
// remember to free the queueBlock afterwards
t_queueBlock *getQueue(t_queue *queue) {
pthread_mutex_lock(&queue->notEmptyLock);
while (queue->head == queue->tail) {
pthread_cond_wait(&queue->notEmpty, &queue->notEmptyLock);
}
pthread_mutex_unlock(&queue->notEmpty);
t_queueBlock item = queue->head;
}