-
Notifications
You must be signed in to change notification settings - Fork 0
/
qlock.h
55 lines (46 loc) · 847 Bytes
/
qlock.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
#include <stdlib.h>
struct msg {
struct msg *next;
};
struct queue {
struct msg *head;
struct msg *tail;
int lock;
};
#define LOCK(q) while (__sync_lock_test_and_set(&(q)->lock,1)) {}
#define UNLOCK(q) __sync_lock_release(&(q)->lock);
static inline struct queue *
qinit(void)
{
struct queue *q = calloc(1, sizeof(*q));
return q;
}
static inline int
push(struct queue *q, struct msg *m)
{
LOCK(q)
if (q->tail) {
q->tail->next = m;
q->tail = m;
} else {
q->head = q->tail = m;
}
UNLOCK(q)
return 0;
}
static inline struct msg *
pop(struct queue *q)
{
struct msg *m;
LOCK(q)
m = q->head;
if (m) {
q->head = m->next;
if (q->head == NULL) {
q->tail = NULL;
}
m->next = NULL;
}
UNLOCK(q)
return m;
}