Ringbuffer

This commit is contained in:
Thomas Klaehn
2019-10-30 11:41:30 +01:00
parent 142e054efc
commit 828d55e708
5 changed files with 110 additions and 32 deletions

View File

@@ -1,28 +1,23 @@
#include <iostream>
#include <pthread.h>
#include "ringbuffer.h"
void *fake_it(void *param)
{
std::cout << "Hello " << __FUNCTION__ << "\r\n";
return NULL;
}
void *poller(void *param)
{
std::cout << "Hello " << __FUNCTION__ << "\r\n";
return NULL;
}
ringbuffer buf;
int main(void) {
pthread_t it_thread, poll_thread;
pthread_create(&it_thread, NULL, fake_it, NULL);
pthread_create(&poll_thread, NULL, poller, NULL);
std::cout << "Hello World!!!" << "\r\n";
pthread_join(it_thread, NULL);
pthread_join(poll_thread, NULL);
buf.write('a');
buf.write('b');
buf.write('c');
char c;
if(buf.read(c)) {
std::cout << c;
}
if(buf.read(c)) {
std::cout << c;
}
if(buf.read(c)) {
std::cout << c;
}
return 0;
}

39
src/ringbuffer.cc Normal file
View File

@@ -0,0 +1,39 @@
#include "ringbuffer.h"
ringbuffer::ringbuffer()
{
head = buffer.begin();
tail = buffer.begin();
}
int ringbuffer::write(char c)
{
if(head - tail == MAX_BUFFER_SIZE) {
return 0;
}
if(head == buffer.end()) {
head = buffer.begin();
}
*head = c;
head++;
return 1;
}
int ringbuffer::read(char& c)
{
if(head - tail == 0) {
return 0;
}
if(tail == buffer.end()) {
tail = buffer.begin();
}
c = *tail;
tail++;
return 1;
}