Page 1 of 1

Accessing Variable from Either ESP32 Core

Posted: Tue Jan 05, 2021 8:35 pm
by gfvalvo
So, if I have a volatile integer variable (say a uint32_t or int16_t), can I safely access it at any time and asynchronously from either core without taking any special precautions?

I assume that anything bigger than a 32-bit variable would be non-atomic and require some type of mutual exclusion.

Re: Accessing Variable from Either ESP32 Core

Posted: Wed Jan 06, 2021 1:17 am
by ESP_Sprite
It depends on what you do with it. If you have one core writing and one core reading, for example, there's no issue. If you have something like read-modify-write (e.g. counter=counter+1) going on, you need to take precautions. Note that this goes for multiple threads in general; having multiple cores doesn't make that much of a difference in when you need to take precautions, just in what precautions you can take. (Also, suggest you look into C/C++ support for atomics. If you use those APIs, everything is more or less guaranteed to work.)

Re: Accessing Variable from Either ESP32 Core

Posted: Wed Jan 06, 2021 3:21 am
by gfvalvo
OK, thanks. After thinking about it more, I realized I need read/modify/write protection across the cores. So, just to be sure I understand, this:

Code: Select all

std::atomic<int16_t> _currentValue;
Will provide atomic protection for an operation like:

Code: Select all

_currentValue += 100;
Also, if the variable is accessed in both an ISR and regular code, do I need:

Code: Select all

volatile std::atomic<int16_t> _currentValue;
Or, are atomic variable "volatile" by defintion?

Thanks again.

Re: Accessing Variable from Either ESP32 Core

Posted: Wed Jan 06, 2021 6:01 am
by ESP_Sprite
I never have done C++ atomics, but that does look correct to me.