-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring_buffer.c
More file actions
71 lines (65 loc) · 1.9 KB
/
Copy pathring_buffer.c
File metadata and controls
71 lines (65 loc) · 1.9 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
// SPDX-License-Identifier: BSD-3-Clause
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "ring_buffer.h"
int ring_buffer_init(so_ring_buffer_t *ring, size_t cap)
{
ring->data = malloc(cap);
ring->read_pos = 0;
ring->write_pos = 0;
ring->len = 0;
ring->cap = cap;
ring->stop = 0;
pthread_mutex_init(&ring->mutex, NULL);
pthread_cond_init(&ring->cond_not_empty, NULL);
pthread_cond_init(&ring->cond_not_full, NULL);
return 0;
}
ssize_t ring_buffer_enqueue(so_ring_buffer_t *ring, void *data, size_t size)
{
pthread_mutex_lock(&ring->mutex);
while (!ring->stop && ring->cap < size + ring->len)
pthread_cond_wait(&ring->cond_not_full, &ring->mutex);
if (ring->stop) {
pthread_mutex_unlock(&ring->mutex);
return -1;
}
memcpy(ring->data + ring->write_pos, data, size);
ring->write_pos = (ring->write_pos + size) % ring->cap;
ring->len += size;
pthread_cond_signal(&ring->cond_not_empty);
pthread_mutex_unlock(&ring->mutex);
return size;
}
ssize_t ring_buffer_dequeue(so_ring_buffer_t *ring, void *data, size_t size)
{
pthread_mutex_lock(&ring->mutex);
while (!ring->stop && ring->len < size)
pthread_cond_wait(&ring->cond_not_empty, &ring->mutex);
if (ring->stop && ring->len < size) {
pthread_mutex_unlock(&ring->mutex);
return -1;
}
memcpy(data, ring->data + ring->read_pos, size);
ring->read_pos = (ring->read_pos + size) % ring->cap;
ring->len -= size;
pthread_cond_signal(&ring->cond_not_full);
pthread_mutex_unlock(&ring->mutex);
return size;
}
void ring_buffer_stop(so_ring_buffer_t *ring)
{
pthread_mutex_lock(&ring->mutex);
ring->stop = 1;
pthread_cond_broadcast(&ring->cond_not_empty);
pthread_cond_broadcast(&ring->cond_not_full);
pthread_mutex_unlock(&ring->mutex);
}
void ring_buffer_destroy(so_ring_buffer_t *ring)
{
free(ring->data);
pthread_mutex_destroy(&ring->mutex);
pthread_cond_destroy(&ring->cond_not_empty);
pthread_cond_destroy(&ring->cond_not_full);
}