Ringbuffer
This commit is contained in:
35
src/main.cc
35
src/main.cc
@@ -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
39
src/ringbuffer.cc
Normal 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;
|
||||
}
|
Reference in New Issue
Block a user