I am building an app in a micro controller. The question is, I'm receiving data in the serial port. It is written using interruptions, what I guess is the same as a thread. So, how could I get this data in the buffer and guarantee some integrity if I can't use lock?
Just disable the receive interrupt when you access protected variables (like the ringbuffer, the read and write position) outside the interrupt, so in your case when you need the number of bytes in the input buffer or you need to pop a byte:
int GetBytesAvailable()
{
int result;
DisableReceiveInterrupt();
result = writePos - readPos;
EnableReceiveInterrupt();
if (result < 0)
result += RINGBUFFER_SIZE;
return result;
}
int GetNextByte()
{
int result = -1;
DisableReceiveInterrupt();
if (readPos != writePos)
{
result = RingBuffer[readPos++];
readPos %= RINGBUFFER_SIZE;
}
EnableReceiveInterrupt();
return result;
}
When the microcontroller receives a byte while the interrupt is disabled. The interrupt handler will be called as soon as you re-enable the interrupt.