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.
Accessing Variable from Either ESP32 Core
-
- Posts: 9746
- Joined: Thu Nov 26, 2015 4:08 am
Re: Accessing Variable from Either ESP32 Core
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
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:
Will provide atomic protection for an operation like:
Also, if the variable is accessed in both an ISR and regular code, do I need:
Or, are atomic variable "volatile" by defintion?
Thanks again.
Code: Select all
std::atomic<int16_t> _currentValue;
Code: Select all
_currentValue += 100;
Code: Select all
volatile std::atomic<int16_t> _currentValue;
Thanks again.
-
- Posts: 9746
- Joined: Thu Nov 26, 2015 4:08 am
Re: Accessing Variable from Either ESP32 Core
I never have done C++ atomics, but that does look correct to me.
Who is online
Users browsing this forum: No registered users and 123 guests