-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_queue.c
104 lines (89 loc) · 2.15 KB
/
data_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
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>
#include "data_queue.h"
int data_queue_init(data_queue * dq, int size) {
if(dq == (void *) 0 || size <= 0) {
return 1;
}
dq->data = (data_queue_element *) malloc(sizeof(data_queue_element) * size);
if(dq->data == (void *) 0) {
return 2;
}
if(pthread_mutex_init(&(dq->mutex), (void *) 0)) {
free((void *)dq->data);
return 3;
}
if(pthread_cond_init(&(dq->cond), (void *) 0)) {
pthread_mutex_destroy(&(dq->mutex));
free((void *)dq->data);
return 4;
}
dq->size = size;
dq->count = 0;
return 0;
}
int data_queue_get_size(const data_queue * dq) {
if(dq == (void *) 0) {
return 0;
}
return dq->size;
}
int data_queue_get_count(data_queue * dq) {
int res = -1;
if(dq != (void *) 0) {
if(!pthread_mutex_lock(&(dq->mutex))) {
res = dq->count;
pthread_mutex_unlock(&(dq->mutex));
}
}
return res;
}
int data_queue_get_data(data_queue * dq, data_queue_element * data) {
int res = -1;
if(dq != (void *) 0) {
if(!pthread_mutex_lock(&(dq->mutex))) {
while(1) {
if(dq->count == 0) {
pthread_cond_wait(&(dq->cond), &(dq->mutex));
continue;
}
dq->count --;
if(data != (void *) 0) {
memcpy((void *) data,
(void *) &(dq->data[dq->count]),
sizeof(data_queue_element));
}
res = 0;
break;
}
pthread_mutex_unlock(&(dq->mutex));
}
}
return res;
}
int data_queue_put_data(data_queue * dq, const struct sockaddr_in * addr, const void * data, int data_len) {
int res = -1;
if(dq != (void *) 0 &&
data != (void *) 0 &&
addr != (void *) 0 &&
data_len > 0 &&
data_len <= TESTDNSD_MAX_PACKET_SIZE) {
if(!pthread_mutex_lock(&(dq->mutex))) {
if(dq->count < dq->size) {
memcpy((void *) &(dq->data[dq->count].addr),
(void *) addr,
sizeof(addr));
memcpy((void *) &(dq->data[dq->count].data),
(void *) data,
data_len);
dq->data[dq->count].data_len = data_len;
dq->count ++;
res = 0;
pthread_cond_signal(&(dq->cond));
}
pthread_mutex_unlock(&(dq->mutex));
}
}
return res;
}