Accessing Variable from Either ESP32 Core

gfvalvo
Posts: 36
Joined: Thu Dec 24, 2020 3:06 pm

Accessing Variable from Either ESP32 Core

Postby gfvalvo » Tue Jan 05, 2021 8:35 pm

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.

ESP_Sprite
Posts: 9746
Joined: Thu Nov 26, 2015 4:08 am

Re: Accessing Variable from Either ESP32 Core

Postby ESP_Sprite » Wed Jan 06, 2021 1:17 am

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.)

gfvalvo
Posts: 36
Joined: Thu Dec 24, 2020 3:06 pm

Re: Accessing Variable from Either ESP32 Core

Postby gfvalvo » Wed Jan 06, 2021 3:21 am

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.

ESP_Sprite
Posts: 9746
Joined: Thu Nov 26, 2015 4:08 am

Re: Accessing Variable from Either ESP32 Core

Postby ESP_Sprite » Wed Jan 06, 2021 6:01 am

I never have done C++ atomics, but that does look correct to me.

Who is online

Users browsing this forum: No registered users and 106 guests