-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue-old.c
94 lines (74 loc) · 1.85 KB
/
queue-old.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
#include <stdlib.h>
#include "queue.h"
#include "mcc.h"
struct queue_object_t
{
struct queue_object_t *next;
void *data;
};
struct queue_t
{
struct queue_object_t **head;
struct queue_object_t **tail;
struct queue_object_t *list;
};
struct queue_t *queue_new()
{
struct queue_t *queue = malloc(sizeof *queue);
queue->list = malloc(sizeof *queue->list);
queue->list->next = NULL;
queue->list->data = NULL;
queue->head = &queue->list;
queue->tail = &queue->list->next;
LOG("[queue_new] %p %p %p\n", queue->list, queue->head, *queue->tail);
return queue;
}
void queue_delete(struct queue_t *queue)
{
int n = 0;
while (queue->list != NULL)
{
struct queue_object_t *qo = queue->list;
queue->list = qo->next;
free(qo->data);
free(qo);
n++;
}
LOG("[queue_delete] Removed %d items from queue\n", n);
}
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? */
*queue->tail = qo;
queue->tail = &qo->next;
/* */
LOG("[queue_produce] Added to queue\n");
int n = 0;
while (queue->list != *queue->head)
{
struct queue_object_t *qo = queue->list;
queue->list = qo->next;
free(qo->data);
free(qo);
n++;
}
if (n > 0) LOG("[queue_produce] Removed %d items from queue\n", n);
return true;
}
int queue_consume(struct queue_t *queue, void **data)
{
struct queue_object_t *next = *queue->head;
next = next->next;
LOG("[queue_consume] %p %p %p\n", queue->list, queue->head, *queue->tail);
if (next != *queue->tail)
{
queue->head = &next->next;
*data = next->next->data;
return true;
}
return false;
}