Embedded_RingBuf_CPP icon indicating copy to clipboard operation
Embedded_RingBuf_CPP copied to clipboard

volatile declaration

Open sslupsky opened this issue 5 years ago • 4 comments

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?

sslupsky avatar Sep 27 '19 22:09 sslupsky

This is in the dev branch.

sslupsky avatar Sep 27 '19 22:09 sslupsky

This is a good point. Some aggressive compilers might optimize and cause this behavior. There are a few solutions:

  1. Declare the _head and `_numElements' as volatile.
  2. 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.

wizard97 avatar Sep 29 '19 22:09 wizard97

Will do.

sslupsky avatar Oct 03 '19 20:10 sslupsky

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.

wizard97 avatar Nov 10 '21 02:11 wizard97