- Jul 23, 2006
- 3,934
- 0
- 76
I'm working on an embedded system that runs a Nios II soft core microprocessor on an Altera FPGA. This device has an rs232 port that receives data via interrupts and I have created a FIFO ring buffer structure (in C) to store these characters until the main program logic can deal with them. Now I've gotten the structure to function correctly however I've realized that there is a possible mutual exclusion issue since the interrupt handlers write to the buffer which at this point isn't thread safe. I realize that this is only a single threaded system, but the ISR is acting as an effective second thread.
I'm trying to think of the best way to approach this since this isn't a typical thread safety issue, since pre-emption can only happen in one direction.
Also feel free to critisize my code... I've mostly done OOP (C++/Java/C#) so I'm still getting the hang of the C programming style.
I'm trying to think of the best way to approach this since this isn't a typical thread safety issue, since pre-emption can only happen in one direction.
Code:
typedef struct{
char* buffer;
int size, read_index, write_index, elements;
} ring_buffer;
void new_ring_buffer(ring_buffer** buf, int size) {
*buf = (ring_buffer*)malloc(sizeof(ring_buffer));
(*buf) -> buffer = (char*)malloc(size * sizeof(char));
(*buf) -> size = size;
(*buf) -> read_index = 0;
(*buf) -> write_index = 0;
(*buf) -> elements = 0;
}
void delete_ring_buffer(ring_buffer* buf) {
free(buf->buffer);
free(buf);
}
char pop_ring_buffer(ring_buffer *buf) {
if (buf->elements == 0) {
// Empty case... not sure this is the optimal solution.
return '\0';
}
char c = buf->buffer[buf->read_index];
buf->read_index = (buf->read_index + 1) % buf->size;
buf->elements--;
return c;
}
void push_ring_buffer(ring_buffer *buf, char c) {
buf->buffer[buf->write_index] = c;
buf->write_index = (buf->write_index + 1) % buf -> size;
buf->elements++;
if (buf->elements > buf->size) {
buf->read_index++;
buf->elements = buf->size;
}
return;
}
void clear_ring_buffer(ring_buffer *buf) {
buf->read_index = buf->write_index;
buf->elements = 0;
}
Also feel free to critisize my code... I've mostly done OOP (C++/Java/C#) so I'm still getting the hang of the C programming style.
Last edited: