-
Notifications
You must be signed in to change notification settings - Fork 0
/
q.h
75 lines (62 loc) · 1.43 KB
/
q.h
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
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct msg {
struct msg *next;
};
struct queue {
uint32_t head;
uint32_t tail;
struct msg **msgs;
struct msg *list;
};
#define CNT 0x10000
#define GP(x) (x % (CNT))
static inline struct queue *
qinit(void)
{
struct queue *q = malloc(sizeof(*q));
bzero(q, sizeof(*q));
q->msgs = calloc(sizeof(struct msg *), CNT);
return q;
}
static inline int
push(struct queue *q, struct msg *m)
{
uint32_t tail = GP(__sync_fetch_and_add(&q->tail, 1));
if (!__sync_bool_compare_and_swap(&q->msgs[tail], NULL, m)) {
struct msg *last;
do {
last = q->list;
m->next = last;
} while (!__sync_bool_compare_and_swap(&q->list, last, m));
}
return 0;
}
static inline struct msg *
pop(struct queue *q)
{
uint32_t head = q->head;
uint32_t h2;
struct msg *list;
if (head == q->tail)
return NULL;
h2 = GP(head);
list = q->list;
if (list) {
struct msg *n = list->next;
if (__sync_bool_compare_and_swap(&q->list, list, n)) {
list->next = NULL;
push(q, list);
}
}
struct msg *m = q->msgs[h2];
if (!m)
return NULL;
if (!__sync_bool_compare_and_swap(&q->head, head, head + 1))
return NULL;
if (!__sync_bool_compare_and_swap(&q->msgs[h2], m, NULL))
return NULL;
return m;
}