make ringbuffer thread safety optional
This commit is contained in:
@ -1,3 +1,5 @@
|
||||
#define RINGBUFFER_THREAD_SAFE
|
||||
|
||||
#include <linux/i2c-dev.h>
|
||||
#include <i2c/smbus.h>
|
||||
#include <sys/ioctl.h>
|
||||
@ -9,7 +11,6 @@
|
||||
#include <stdint.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include "global.h"
|
||||
#include "ringbuffer.h"
|
||||
|
@ -1,9 +1,12 @@
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
|
||||
#include "ringbuffer.h"
|
||||
|
||||
void _ringBufferIncReader(struct ringBuffer *buf) {
|
||||
@ -34,32 +37,46 @@ void ringBufferCreate(int blocks, size_t blockSize, struct ringBuffer *out) {
|
||||
out->blockSize = blockSize;
|
||||
out->reader = out->buffer;
|
||||
out->writer = out->buffer;
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_init(&out->mutex, NULL);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ringBufferDestroy(struct ringBuffer *buf) {
|
||||
free(buf->buffer);
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_destroy(&buf->mutex);
|
||||
#endif
|
||||
}
|
||||
|
||||
int ringBufferRead(struct ringBuffer *buf, void *out) {
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_lock(&buf->mutex);
|
||||
#endif
|
||||
if (buf->reader != buf->writer) {
|
||||
// we have data to read
|
||||
memcpy(out, buf->reader, buf->blockSize);
|
||||
_ringBufferIncReader(buf);
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_unlock(&buf->mutex);
|
||||
#endif
|
||||
return 0;
|
||||
} else {
|
||||
// nothing to read
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_unlock(&buf->mutex);
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void ringBufferWrite(struct ringBuffer *buf, void *in) {
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_lock(&buf->mutex);
|
||||
#endif
|
||||
memcpy(buf->writer, in, buf->blockSize);
|
||||
_ringBufferIncWriter(buf);
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_unlock(&buf->mutex);
|
||||
#endif
|
||||
}
|
||||
|
@ -6,7 +6,9 @@ struct ringBuffer {
|
||||
size_t blockSize;
|
||||
void *reader;
|
||||
void *writer;
|
||||
#ifdef RINGBUFFER_THREAD_SAFE
|
||||
pthread_mutex_t mutex;
|
||||
#endif
|
||||
};
|
||||
|
||||
void ringBufferCreate(int blocks, size_t blockSize, struct ringBuffer *out);
|
||||
|
Reference in New Issue
Block a user