-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_mod.c
More file actions
100 lines (87 loc) · 2.21 KB
/
queue_mod.c
File metadata and controls
100 lines (87 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "queue_mod.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
/**
* q queue is implemented with a linked list of queue_nodes.
*/
typedef struct queue_node {
void *data;
struct queue_node *next;
} queue_node;
struct queue {
/* queue_node pointers to the head and tail of the queue */
queue_node *head, *tail;
/* The number of elements in the queue */
ssize_t size;
/**
* The maximum number of elements the queue can hold.
* max_size is non-positive if the queue does not have a max size.
*/
ssize_t max_size;
/* Mutex and Condition Variable for thread-safety */
pthread_cond_t cv;
pthread_mutex_t m;
};
queue *queue_create(size_t max_size) {
struct queue * ret = malloc(sizeof(queue));
ret->max_size = max_size;
ret->size = 0;
ret->tail = NULL;
ret->head = NULL;
pthread_cond_init(&ret->cv, NULL);
pthread_mutex_init(&ret->m, NULL);
return ret;
}
void queue_destroy(queue *q) {
queue_node * destroy = q->tail;
queue_node * temp = NULL;
while (destroy) {
temp = destroy;
destroy = destroy->next;
free(temp);
}
pthread_mutex_destroy(&(q->m));
pthread_cond_destroy(&(q->cv));
free(q);
}
void queue_push(queue *q, void *data) {
pthread_mutex_lock(&q->m);
while (q->max_size > 0 && q->size >= q->max_size) {
pthread_cond_wait(&q->cv, &q->m);
}
queue_node * elem = malloc(sizeof(queue_node));
elem->data = data;
elem->next = NULL;
if (q->head != NULL) {
q->head->next = elem;
}
q->head = elem;
if (q->tail == NULL) {
q->tail = elem;
}
q->size = q->size + 1;
if (q->size > 0) {
pthread_cond_broadcast(&q->cv);
}
pthread_mutex_unlock(&q->m);
}
void * queue_pull(queue *q) {
pthread_mutex_lock(&q->m);
while (q->size == 0) {
pthread_cond_wait(&q->cv, &q->m);
}
void * d = q->tail->data;
queue_node * temp = q->tail;
q->tail = q->tail->next;
free(temp);
q->size--;
if (q->tail == NULL) {
q->head = NULL;
}
if ( q->size < q->max_size && q->max_size > 0) {
pthread_cond_broadcast(&q->cv);
}
pthread_mutex_unlock(&q->m);
return d;
}