-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_pool.c
131 lines (99 loc) · 2.55 KB
/
buffer_pool.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
#include "buffer_pool.h"
#include <stdlib.h>
#include <time.h>
#include "hardware/sync.h"
static bool _pool_buffer_alloc(pool_t *p, uint index);
static void _pool_buffer_free(pool_t *p, uint index);
bool pool_init(pool_t *p, size_t buffer_size, uint buffer_count) {
srand(time(NULL));
p->buffer_size = 0;
p->buffer_count = 0;
p->buffers = calloc(buffer_count, sizeof(buffer_t));
if (p->buffers == NULL) {
return false;
}
p->buffer_size = buffer_size;
mutex_init(&p->pool_mutex);
for (uint i = 0; i < buffer_count; i++) {
if (!_pool_buffer_alloc(p, i)) {
pool_destroy(p);
return false;
}
p->buffer_count++;
}
return true;
}
void pool_destroy(pool_t *p) {
if (p == NULL) {
return;
}
mutex_enter_blocking(&p->pool_mutex);
for (uint i = 0; i < p->buffer_count; i++) {
_pool_buffer_free(p, i);
}
p->buffer_count = 0;
if (p->buffers != NULL) {
free(p->buffers);
p->buffers = NULL;
}
mutex_exit(&p->pool_mutex);
}
buffer_t* pool_buffer_claim(pool_t *p) {
mutex_enter_blocking(&p->pool_mutex);
buffer_t *buffer = NULL;
for (uint i = 0; i < p->buffer_count; i++) {
if (!p->buffers[i].in_use) {
p->buffers[i].handle = rand();
p->buffers[i].in_use = true;
buffer = &p->buffers[i];
break;
}
}
mutex_exit(&p->pool_mutex);
return buffer;
}
void pool_buffer_release(pool_t *p, uint buffer_handle) {
mutex_enter_blocking(&p->pool_mutex);
for (uint i = 0; i < p->buffer_count; i++) {
if (p->buffers[i].handle == buffer_handle) {
p->buffers[i].handle = 0;
p->buffers[i].in_use = false;
break;
}
}
mutex_exit(&p->pool_mutex);
}
buffer_t* pool_buffer_get(pool_t *p, uint buffer_handle) {
mutex_enter_blocking(&p->pool_mutex);
buffer_t *buffer = NULL;
for (uint i = 0; i < p->buffer_count; i++) {
if (p->buffers[i].handle == buffer_handle && p->buffers[i].in_use) {
buffer = &p->buffers[i];
break;
}
}
if (buffer == NULL) {
return NULL;
}
mutex_exit(&p->pool_mutex);
return buffer;
}
static bool _pool_buffer_alloc(pool_t *p, uint index) {
p->buffers[index].handle = 0;
p->buffers[index].in_use = false;
p->buffers[index].data = malloc(p->buffer_size);
p->buffers[index].size = p->buffer_size;
if (p->buffers[index].data == NULL) {
return false;
}
return true;
}
static void _pool_buffer_free(pool_t *p, uint index) {
if (index >= p->buffer_count) {
return;
}
if (p->buffers[index].data != NULL) {
free(p->buffers[index].data);
}
p->buffers[index].data = NULL;
}