slight update
[rrq/rrqnet.git] / queue.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "queue.h"
4
5 void Queue_addItem(Queue *list,QueueItem *item) {
6     if ( pthread_mutex_lock( &list->mutex ) ) {
7         perror( "FATAL" );
8         exit( 1 );
9     }
10     item->next = 0; // just in case
11     if ( list->last ) {
12         list->last->next = item;
13     } else {
14         list->head = item;
15     }
16     list->last = item;
17     if ( sem_post( &list->count ) ) {
18         perror( "FATAL" );
19         exit( 1 );
20     }
21     if ( pthread_mutex_unlock( &list->mutex ) ) {
22         perror( "FATAL" );
23         exit( 1 );
24     }
25 }
26
27 QueueItem *Queue_getItem(Queue *list) {
28     QueueItem *item;
29     if ( sem_wait( &list->count ) ) {
30         perror( "FATAL" );
31         exit( 1 );
32     }
33     if ( pthread_mutex_lock( &list->mutex ) ) {
34         perror( "FATAL" );
35         exit( 1 );
36     }
37     item = list->head;
38     list->head = item->next;
39     if ( list->head == 0 ) {
40         list->last = 0;
41     }
42     if ( pthread_mutex_unlock( &list->mutex ) ) {
43         perror( "FATAL" );
44         exit( 1 );
45     }
46     return item;
47 }
48
49 void Queue_initialize(Queue *list,int n,size_t size) {
50     if ( pthread_mutex_lock( &list->mutex ) ) {
51         perror( "FATAL" );
52         exit( 1 );
53     }
54     if ( list->head == 0 ) {
55         int i = 0;
56         for ( ; i < n; i++ ) {
57             QueueItem *x = (QueueItem *) calloc( 1, size );
58             if ( list->head ) {
59                 list->last->next = x;
60             } else {
61                 list->head = x;
62             }
63             list->last = x;
64         }
65         sem_init( &list->count, 0, n );
66     }
67     if ( pthread_mutex_unlock( &list->mutex ) ) {
68         perror( "FATAL" );
69         exit( 1 );
70     }
71 }