-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
99 lines (81 loc) · 1.81 KB
/
queue.c
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
#include <stdlib.h>
#include <pthread.h>
#include "queue.h"
#include "mcc.h"
struct queue_object_t
{
struct queue_object_t *next;
void *data;
};
struct queue_t
{
pthread_mutex_t produce_mutex;
pthread_mutex_t consume_mutex;
struct queue_object_t *head;
struct queue_object_t *tail;
struct queue_object_t *divider;
};
struct queue_t *queue_new(void)
{
struct queue_t *queue = malloc(sizeof *queue);
struct queue_object_t *qo = malloc(sizeof *qo);
qo->next = NULL;
qo->data = NULL;
queue->head = qo;
queue->tail = qo;
queue->divider = qo;
pthread_mutex_init(&queue->produce_mutex, NULL);
pthread_mutex_init(&queue->consume_mutex, NULL);
return queue;
}
void queue_delete(struct queue_t *queue)
{
int n = 0;
while (queue->head != NULL)
{
struct queue_object_t *qo = queue->head;
queue->head = qo->next;
//free(qo->data);
free(qo);
n++;
}
pthread_mutex_destroy(&queue->produce_mutex);
pthread_mutex_destroy(&queue->consume_mutex);
free(queue);
}
int queue_produce(struct queue_t *queue, void *data)
{
if (queue == NULL) return false;
struct queue_object_t *qo = malloc(sizeof *qo);
qo->next = NULL;
qo->data = data;
/* Lock needed? */
pthread_mutex_lock(&queue->produce_mutex);
queue->tail->next = qo;
queue->tail = qo;
/* */
int n = 0;
while (queue->head != queue->divider)
{
struct queue_object_t *qo = queue->head;
queue->head = qo->next;
//free(qo->data);
free(qo);
n++;
}
pthread_mutex_unlock(&queue->produce_mutex);
return true;
}
int queue_consume(struct queue_t *queue, void **data)
{
pthread_mutex_lock(&queue->consume_mutex);
if (queue->divider != queue->tail)
{
*data = queue->divider->next->data;
queue->divider = queue->divider->next;
pthread_mutex_unlock(&queue->consume_mutex);
return true;
}
pthread_mutex_unlock(&queue->consume_mutex);
return false;
}