forked from the-tcpdump-group/tcpdump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkt_queue.c
62 lines (55 loc) · 1.29 KB
/
pkt_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
/*
* Copyright (C) 2014 Yuzhong Wen<[email protected]>
*
* Distributed under terms of the MIT license.
*/
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include "pkt_queue.h"
void init_queue(struct queue_root **root)
{
*root = (struct queue_root*) malloc(sizeof(struct queue_root));
if (root == NULL) {
printf("malloc failed");
exit(1);
}
(*root)->head = (struct queue_node*) malloc(sizeof(struct queue_node)); /* Sentinel node */
(*root)->tail = (*root)->head;
(*root)->head->n = NULL;
(*root)->head->next = NULL;
}
int queue_add(struct queue_root *root, void *val)
{
struct queue_node *n;
struct queue_node *node = (struct queue_node *)malloc(sizeof(struct queue_node));
node->n = val;
node->next = NULL;
while (1) {
n = root->tail;
if (__sync_bool_compare_and_swap(&(n->next), NULL, node)) {
break;
} else {
__sync_bool_compare_and_swap(&(root->tail), n, n->next);
}
}
__sync_bool_compare_and_swap(&(root->tail), n, node);
return 1;
}
void *queue_get(struct queue_root *root)
{
struct queue_node *n;
void *val;
while (1) {
n = root->head;
if (n->next == NULL) {
return NULL;
}
if (__sync_bool_compare_and_swap(&(root->head), n, n->next)) {
break;
}
}
val = (void *) n->next->n;
free(n);
return val;
}