diff options
author | Robert Gustafsson <robg@student.chalmers.se> | 2017-09-29 15:04:25 +0200 |
---|---|---|
committer | Andreas Lindhé <andreas@lindhe.io> | 2017-10-09 12:14:35 +0200 |
commit | f41e21a2bbcd1bbf559212092f0f2b119e446756 (patch) | |
tree | 11157d18f5691749e628d443c96eb91d8a3edd63 | |
parent | 11187a331cc132b990785dfe0012054bf686a5d4 (diff) | |
download | midbro-f41e21a2bbcd1bbf559212092f0f2b119e446756.tar.gz midbro-f41e21a2bbcd1bbf559212092f0f2b119e446756.tar.bz2 |
Add blocking wait when buffer is empty
-rw-r--r-- | broccoli/fifoqueue.c | 17 | ||||
-rw-r--r-- | broccoli/midbropasad.c | 3 |
2 files changed, 13 insertions, 7 deletions
diff --git a/broccoli/fifoqueue.c b/broccoli/fifoqueue.c index 6676484..dfb8464 100644 --- a/broccoli/fifoqueue.c +++ b/broccoli/fifoqueue.c @@ -2,6 +2,7 @@ #include <pthread.h> pthread_mutex_t lock; +pthread_mutex_t bufferEmptyBlock; Fifo_q * init_queue(int size) @@ -11,11 +12,15 @@ init_queue(int size) q->tail = NULL; q->maxSize = size; q->currentSize = 0; - if (pthread_mutex_init(&lock, NULL) != 0) { printf("WARNING: Couldn't initialize lock\n"); } + if (pthread_mutex_init(&bufferEmptyBlock, NULL) != 0) + { + printf("WARNING: Couldn't initialize blocking lock\n"); + } + pthread_mutex_lock(&bufferEmptyBlock); return q; } @@ -52,14 +57,14 @@ add_to_queue(Fifo_q * q, Sensor_t * sensor) Queue_t * new_elem = (Queue_t *) malloc(sizeof(Queue_t *)); new_elem->next = NULL; new_elem->sensor = sensor; - if(is_empty(q)) + if(is_empty(q)){ q->head = new_elem; - else + pthread_mutex_unlock(&bufferEmptyBlock); + }else q->tail->next = new_elem; q->tail = new_elem; q->currentSize++; pthread_mutex_unlock(&lock); - print_queue(q); return 1; } @@ -67,11 +72,11 @@ add_to_queue(Fifo_q * q, Sensor_t * sensor) pop_from_queue(Fifo_q * q) { - pthread_mutex_lock(&lock); if(is_empty(q)){ perror("The queue is empty"); - exit(-1); + pthread_mutex_lock(&bufferEmptyBlock); } + pthread_mutex_lock(&lock); Queue_t * head = q->head; q->head = q->head->next; Sensor_t * sensor = head->sensor; diff --git a/broccoli/midbropasad.c b/broccoli/midbropasad.c index 6db59a5..70a290f 100644 --- a/broccoli/midbropasad.c +++ b/broccoli/midbropasad.c @@ -20,7 +20,8 @@ main(int argc, char **argv) start_data_capture(q); while(true){ printf("Main thread\n"); - sleep(2); + sleep(10); + print_queue(q); } free(q); return 0; |