annotate src/c/queue.c @ 1693:27d68ccb2c9e

New release
author Adam Chlipala <adam@chlipala.net>
date Sat, 10 Mar 2012 13:13:15 -0500
parents 452b14d88a10
children
rev   line source
adamc@1268 1 #include "config.h"
adamc@1268 2
adamc@859 3 #include <stdlib.h>
adamc@859 4
adamc@859 5 #include <pthread.h>
adamc@859 6
adamc@859 7 typedef struct node {
adamc@859 8 int fd;
adamc@859 9 struct node *next;
adamc@859 10 } *node;
adamc@859 11
adamc@859 12 static node front = NULL, back = NULL;
adamc@859 13
adamc@859 14 static int empty() {
adamc@859 15 return front == NULL;
adamc@859 16 }
adamc@859 17
adamc@859 18 static void enqueue(int fd) {
adamc@859 19 node n = malloc(sizeof(struct node));
adamc@859 20
adamc@859 21 n->fd = fd;
adamc@859 22 n->next = NULL;
adamc@859 23 if (back)
adamc@859 24 back->next = n;
adamc@859 25 else
adamc@859 26 front = n;
adamc@859 27 back = n;
adamc@859 28 }
adamc@859 29
adamc@859 30 static int dequeue() {
adamc@859 31 int ret = front->fd;
marco-oweber@1330 32 node n = front->next;
marco-oweber@1330 33 free(front);
adamc@859 34
marco-oweber@1330 35 front = n;
marco-oweber@1330 36
adamc@859 37 if (!front)
adamc@859 38 back = NULL;
adamc@859 39
adamc@859 40 return ret;
adamc@859 41 }
adamc@859 42
adamc@859 43 static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
adamc@859 44 static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
adamc@859 45
adamc@859 46 int uw_dequeue() {
adamc@859 47 int sock;
adamc@859 48
adamc@859 49 pthread_mutex_lock(&queue_mutex);
adamc@859 50 while (empty())
adamc@859 51 pthread_cond_wait(&queue_cond, &queue_mutex);
adamc@859 52 sock = dequeue();
adamc@859 53 pthread_mutex_unlock(&queue_mutex);
adamc@859 54
adamc@859 55 return sock;
adamc@859 56 }
adamc@859 57
adamc@859 58 void uw_enqueue(int new_fd) {
adamc@859 59 pthread_mutex_lock(&queue_mutex);
adamc@859 60 enqueue(new_fd);
adamc@859 61 pthread_cond_broadcast(&queue_cond);
adamc@859 62 pthread_mutex_unlock(&queue_mutex);
adamc@859 63 }