ESP32 S3 accessing the same variable from both cores

Slinisa
Posts: 26
Joined: Sat Oct 07, 2023 8:21 am

ESP32 S3 accessing the same variable from both cores

Postby Slinisa » Sun Feb 18, 2024 3:03 pm

I have problems when accessing the same variable. I tried declaring an integer as volatile and then non volatile and the behaviour is not consistent. Sometimes volatile helps to get the right value, sometimes not. Also sometimes accessing a volatile variable affects accessing real values in non volatile vars, for example I have

volatile int Mode;
int test;

If I do something like

Mode=1;
if (Mode) Serial.println ("Test : "+String(test));

will have different result (if other core is writing to a variable "test" at the same time) then just

Serial.println ("Test : "+String(test));


Although the result should be the same. I did objdump and found that assembler instruction memw is executed when accessing a volatile var, which does "Order memory accesses before with memory access after". i.e. something like update values in cache from the memory.

My question is: are there some quidelines on how to manage data access from two cores?

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

Re: ESP32 S3 accessing the same variable from both cores

Postby ESP_Sprite » Mon Feb 19, 2024 3:26 am

Can you post your entire project?

Slinisa
Posts: 26
Joined: Sat Oct 07, 2023 8:21 am

Re: ESP32 S3 accessing the same variable from both cores

Postby Slinisa » Mon Feb 19, 2024 11:38 am

That's around 200 kB of code already (391713 bytes of program storage space), so I don't think it's a good idea :D
Anyway, I figured it out. I only use volatile variables when the change is needed to be noticed promptly by another core. For other types of variables non volatile is fast enough.

User avatar
ok-home
Posts: 48
Joined: Sun May 02, 2021 7:23 pm
Location: Russia Novosibirsk
Contact:

Re: ESP32 S3 accessing the same variable from both cores

Postby ok-home » Mon Feb 19, 2024 1:39 pm

hi
volatile variables do not protect variables from date races
esp idf provides two possible protection options depending on application requirements
mutex and spinlock

MicroController
Posts: 1221
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: ESP32 S3 accessing the same variable from both cores

Postby MicroController » Tue Feb 20, 2024 9:54 pm

Although the result should be the same.
This is a common misconception about what volatile does and does not do, especially when it comes to the interactions between volatile and non-volatile accesses.
A 'clean and simple' approach using locks/mutexes instead of volatile variables is more promising.

Who is online

Users browsing this forum: No registered users and 120 guests