-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
158 lines (133 loc) · 2.63 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/**
* 事件队列
* @file queue.c
* @author zhaowei
* @ingroup memlink
* @{
*/
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "queue.h"
#include "myconfig.h"
#include "logfile.h"
#include "zzmalloc.h"
Queue*
queue_create()
{
Queue *q;
q = (Queue*)zz_malloc(sizeof(Queue));
if (NULL == q) {
DERROR("malloc Queue error!\n");
MEMLINK_EXIT;
return NULL;
}
memset(q, 0, sizeof(Queue));
int ret = pthread_mutex_init(&q->lock, NULL);
if (-1 == ret) {
DERROR("pthread_mutex_init error!\n");
MEMLINK_EXIT;
return NULL;
}
return q;
}
void
queue_destroy(Queue *q)
{
QueueItem *item, *tmp;
item = q->head;
while (item) {
tmp = item;
item = item->next;
zz_free(tmp);
}
pthread_mutex_destroy(&q->lock);
zz_free(q);
}
int
queue_size(Queue *q)
{
int count = 0;
QueueItem *item;
pthread_mutex_lock(&q->lock);
item = q->head;
while (item) {
count++;
item = item->next;
}
pthread_mutex_lock(&q->lock);
return count;
}
int
queue_append(Queue *q, Conn *conn)
{
int ret = 0;
QueueItem *item = (QueueItem*)zz_malloc(sizeof(QueueItem));
if (NULL == item) {
DERROR("malloc QueueItem error!\n");
MEMLINK_EXIT;
//goto queue_append_over;
}
item->conn = conn;
item->next = NULL;
pthread_mutex_lock(&q->lock);
if (q->tail == NULL) {
q->tail = item;
q->head = item;
}else{
q->tail->next = item;
q->tail = item;
}
//queue_append_over:
pthread_mutex_unlock(&q->lock);
return ret;
}
int
queue_remove_last(Queue *q, Conn *conn)
{
QueueItem *item, *prev = NULL, *last = NULL;
pthread_mutex_lock(&q->lock);
item = q->head;
while (item) {
prev = last;
last = item;
item = item->next;
}
if (last && last->conn == conn) {
if (prev) {
prev->next = NULL;
}else{
q->head = NULL;
}
close(conn->sock);
zz_free(conn);
zz_free(last);
}
pthread_mutex_unlock(&q->lock);
return 0;
}
QueueItem*
queue_get(Queue *q)
{
QueueItem *ret;
pthread_mutex_lock(&q->lock);
ret = q->head;
q->head = q->tail = NULL;
pthread_mutex_unlock(&q->lock);
return ret;
}
void
queue_free(Queue *q, QueueItem *item)
{
QueueItem *tmp;
//DINFO("queue free head:%p\n", item);
while (item) {
tmp = item;
item = item->next;
zz_free(tmp);
}
}
/**
* @}
*/