-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuf.c
More file actions
136 lines (100 loc) · 2.3 KB
/
buf.c
File metadata and controls
136 lines (100 loc) · 2.3 KB
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
/**
* buf.h -- thread safety producer and consumer model
*
* @author tony <tunghai.huo@gmail.com>
*
*/
#include "buf.h"
buf_handle * buf_init(int buf_size, int entry_size)
{
int ret;
if(buf_size <= 0)
return NULL;
if(entry_size <= 0)
return NULL;
buf_handle * hand = (buf_handle*)malloc(sizeof(buf_handle));
if(hand == NULL)
return NULL;
hand->buffer = (void **)malloc(sizeof(void *)*buf_size);
hand->buf_size = buf_size;
hand->count = 0;
if(hand->buffer == NULL)
return NULL;
hand->magic = sizeof(buf_handle);
hand->entry_size = entry_size;
hand->in = 0;
hand->out = 0;
ret = sem_init(&hand->mutex,0, 1);
if(ret != 0)
return NULL;
ret = sem_init(&hand->empty,0, buf_size);// maybe bug
if(ret != 0)
return NULL;
ret = sem_init(&hand->full,0, 0);
if(ret != 0)
return NULL;
return hand;
}
int buf_put(buf_handle * hand,void * entry)
{
if(hand == NULL)
return -1;
if(entry == NULL)
return -1;
if(hand->magic != sizeof(buf_handle))
return -1;
if(sizeof(entry) != ((struct buf_handle *)hand)->entry_size)
return -1;
sem_wait(&hand->empty);
sem_wait(&hand->mutex);
hand->buffer[hand->in++] = entry; //store pointer
hand->in %= hand->buf_size;
hand->count++;
sem_post(&hand->mutex);
sem_post(&hand->full);
return 0;
}
void * buf_get(buf_handle * hand)
{
if(hand == NULL)
return NULL;
void * entry = NULL;
sem_wait(&hand->full); //down
sem_wait(&hand->mutex); //down
entry = hand->buffer[hand->out++];
hand->out %= hand->buf_size;
hand->count--;
sem_post(&hand->mutex);//up
sem_post(&hand->empty);//up
return entry;
}
int buf_getall(buf_handle * hand, void *** entries)
{
if(hand == NULL)
return -1;
int buf_size = hand->count; //maybe bugs FIXME
*entries = (void **)malloc(buf_size * sizeof(void *));
memset(entries, 0, buf_size * sizeof(void *));
int i=0;
for(;i<buf_size;i++)
{
*entries[i] = buf_get(hand);
}
return buf_size;
}
int buf_uninit(buf_handle * hand)
{
if(hand == NULL)
return -1;
if(hand->magic != sizeof(buf_handle))
return -1;
if(((struct buf_handle*)hand)->mutex != 0)
sem_destroy(&hand->mutex);
if(((struct buf_handle*)hand)->empty != 0)
sem_destroy(&hand->empty);
if(((struct buf_handle*)hand)->full != 0)
sem_destroy(&hand->full);
if(hand != NULL)
free(hand);
return 0;
}