forked from koparasy/approximate_runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
110 lines (87 loc) · 1.46 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
100
101
102
103
104
105
106
107
108
109
#include <string.h>
#include <stdio.h>
#include "queue.h"
#include <sched.h>
int queue_make_element(element_t **element, void *data)
{
element_t *el;
el = (element_t*) calloc(1, sizeof(element_t));
if ( el == NULL )
{
return 2;
}
el->next = NULL;
el->data = data;
*element = el;
return 0;
}
int queue_init(queue_t** queue)
{
queue_t *q;
q = (queue_t*) calloc(1, sizeof(queue_t));
if ( q == NULL )
return 2;
q->head = (element_t*) calloc(1, sizeof(element_t));
q->tail = q->head;
if ( q->head == NULL )
{
free(q);
return 2;
}
*queue = q;
return 0;
}
int queue_destroy(queue_t **queue)
{
element_t *el;
if ( *queue == NULL )
return 1;
for ( el = (*queue)->head->next; el != NULL; )
{
element_t *n = el->next;
free(el->data);
free(el);
el = n;
}
free((*queue)->head);
free(*queue);
*queue = NULL;
return 0;
}
int queue_push(queue_t *queue, element_t *element)
{
element_t *tail;
do
{
tail = queue->tail;
if ( __sync_bool_compare_and_swap(&(tail->next), NULL, element) )
{
if ( __sync_bool_compare_and_swap(&(queue->tail), tail, element) )
{
return 0;
}
}
sched_yield();
}
while(1);
}
int queue_pop(queue_t *queue, void** data)
{
element_t *head;
do
{
head = queue->head;
if (head->next == NULL)
{
*data = NULL;
return 2;
}
if ( __sync_bool_compare_and_swap(&(queue->head), head, head->next) )
{
*data = head->next->data;
return 0;
}
sched_yield();
}
while ( 1 );
}