summaryrefslogtreecommitdiff
path: root/queue.c
diff options
context:
space:
mode:
authorTom Harley2020-01-24 05:15:35 +0000
committerTom Harley2020-01-24 05:15:35 +0000
commitc9f0de12be31eea463bf022f3eee76490b30f8dc (patch)
treea80718ff00fa2dcb1c52c2af6828feffc7f89d8b /queue.c
downloadparapat-master.tar.gz
parapat-master.zip

Initial commit

HEADmaster
Diffstat (limited to 'queue.c')
-rw-r--r--queue.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/queue.c b/queue.c
new file mode 100644
index 0000000..18530f3
--- /dev/null
+++ b/queue.c
@@ -0,0 +1,63 @@
+#include <semaphore.h>
+#include <pthread.h>
+#include <assert.h>
+
+#include "debug.h"
+
+#include "queue.h"
+
+int init_queue(queue *q) {
+ int i;
+ sem_init(&q->size, 0, 0);
+ pthread_mutex_init(&q->mtx, NULL);
+ q->front = 0;
+ q->back = 0;
+ for (i = 0; i < 100; ++i) {
+ q->elements[i] = NULL;
+ }
+ debug(("initialised queue %p\n", (void *) q));
+
+ return 0;
+}
+
+int enqueue(queue *q, void *v) {
+ pthread_mutex_lock(&q->mtx);
+
+ q->elements[q->front] = v;
+ q->front = (q->front + 1) % 100;
+
+ debug(("%p enqueued in %p\n", v, (void *) q));
+
+ sem_post(&q->size);
+ pthread_mutex_unlock(&q->mtx);
+ return 0;
+}
+
+int dequeue(queue *q, void **v) {
+ int result;
+
+ sem_wait(&q->size);
+ pthread_mutex_lock(&q->mtx);
+
+ if (q->back == q->front) {
+ sem_post(&q->size);
+ result = 1;
+
+ debug(("found %p to be closed\n", (void *) q));
+ } else {
+ *v = q->elements[q->back];
+ q->back = (q->back + 1) % 100;
+ result = 0;
+
+ debug(("%p dequeued from %p\n", *v, (void *) q));
+ }
+
+ pthread_mutex_unlock(&q->mtx);
+ return result;
+}
+
+int pq_close(queue *q) {
+ sem_post(&q->size);
+ debug(("%p closed\n", (void *) q));
+ return 0;
+}