-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathringbuffer.c
96 lines (81 loc) · 2.21 KB
/
ringbuffer.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
/**
* Implements a simple lock-free circular buffer that can be used as a bounded queue.
*
* This implementation is safe for multiple producers and consumers.
*
* Dennis Futselaar (C) 2016. Released under the 2-clause BSD license.
*/
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ringbuffer.h"
RingBuffer *ringBufferInit(int64_t size)
{
RingBuffer *buffer = malloc(sizeof(RingBuffer) + size * sizeof(void*));
buffer->readPointer = 0;
buffer->writePointer = 0;
buffer->size = size;
memset(buffer->buffer, 1, size * sizeof(void*));
return buffer;
}
int ringBufferAdd(RingBuffer *buffer, void *value)
{
uint64_t readPointer;
uint64_t writePointer;
uint64_t realPointer;
void *oldValue;
while (1)
{
readPointer = __atomic_load_n(&buffer->readPointer, __ATOMIC_SEQ_CST);
writePointer = __atomic_load_n(&buffer->writePointer, __ATOMIC_SEQ_CST);
if (writePointer - readPointer >= buffer->size)
{
return 0;
}
realPointer = writePointer % buffer->size;
oldValue = buffer->buffer[realPointer];
if (!oldValue || !__atomic_compare_exchange_n(&buffer->buffer[realPointer], &oldValue, 0, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
{
continue;
}
if (__atomic_compare_exchange_n(&buffer->writePointer, &writePointer, writePointer + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
{
break;
}
void *allocValue = NULL;
__atomic_compare_exchange_n(&buffer->buffer[realPointer], &allocValue, oldValue, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
}
buffer->buffer[realPointer] = value;
return 1;
}
void * ringBufferGet(RingBuffer *buffer)
{
uint64_t readPointer;
uint64_t writePointer;
uint64_t realPointer;
void *result;
while (1)
{
writePointer = __atomic_load_n(&buffer->writePointer, __ATOMIC_SEQ_CST);
readPointer = __atomic_load_n(&buffer->readPointer, __ATOMIC_SEQ_CST);
if (readPointer >= writePointer)
{
return NULL;
}
realPointer = readPointer % buffer->size;
result = buffer->buffer[realPointer];
if (!result)
{
return NULL;
}
if (__atomic_compare_exchange_n(&buffer->readPointer, &readPointer, readPointer + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
{
break;
}
}
return result;
}
void ringBufferDestroy(RingBuffer *buffer)
{
free(buffer);
}