Embedded_RingBuf_CPP
Embedded_RingBuf_CPP copied to clipboard
volatile declaration
I think I may have found one issue here:
https://github.com/wizard97/Embedded_RingBuf_CPP/blob/bfe49d18f900220527f130c4a170369d2968493b/src/RingBufCPP.h#L214-L215
Do these variables need to be declared "volatile"? When I compiled a sketch without the volatile declaration, the isEmpty() member function always came back false.
Does this suggest _buf should be declared volatile as well?
This is in the dev branch.
This is a good point. Some aggressive compilers might optimize and cause this behavior. There are a few solutions:
- Declare the
_head
and `_numElements' as volatile. - Declare the whole buffer as volatile.
I'm not sure about needing to declare the underlying buffer as volatile... I'm not sure if compilers are allowed to optimize entire arrays in registers. I doubt they are because most ISAs do not have an efficient instruction that supports indexing into the register file based on a dynamic offset.
Feel free to make a pull request to declare those members as volatile and I will accept it.
Will do.
I know this issue is old, but commenting anyways. Volatile is deprecated in modern C++ for almost every use case (including this one). The correct solution would be inserting a compiler memory barrier upon entry and exit of the atomic guard. This will force the compiler to synchronize the backing memory corresponding to the registers contents.