wangzhengquan
2020-05-25 ff31a5b78ebe4b4348ed7fd572941b23a87414c2
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
typedef struct _Node Node;
typedef struct _Queue Queue;
 
struct _Node {
    void *data;
    Node *next;
};
 
struct _Queue {
    Node *head;
    Node *tail;
};
 
Queue*
queue_new(void)
{
    Queue *q = g_slice_new(sizeof(Queue));
    q->head = q->tail = g_slice_new0(sizeof(Node));
    return q;
}
 
void
queue_enqueue(Queue *q, gpointer data)
{
    Node *node, *tail, *next;
 
    node = g_slice_new(Node);
    node->data = data;
    node->next = NULL;
 
    while (TRUE) {
        tail = q->tail;
        next = tail->next;
        if (tail != q->tail)
            continue;
 
        if (next != NULL) {
            CAS(&q->tail, tail, next);
            continue;
        }
 
        if (CAS(&tail->next, null, node)
            break;
    }
 
    CAS(&q->tail, tail, node);
}
 
gpointer
queue_dequeue(Queue *q)
{
    Node *node, *tail, *next;
 
    while (TRUE) {
        head = q->head;
        tail = q->tail;
        next = head->next;
        if (head != q->head)
            continue;
 
        if (next == NULL)
            return NULL; // Empty
 
        if (head == tail) {
            CAS(&q->tail, tail, next);
            continue;
        }
 
        data = next->data;
        if (CAS(&q->head, head, next))
            break;
    }
 
    g_slice_free(Node, head); // This isn't safe
    return data;
}