Page 1 of 1

ESP32 S3 accessing the same variable from both cores

Posted: Sun Feb 18, 2024 3:03 pm
by Slinisa
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?

Re: ESP32 S3 accessing the same variable from both cores

Posted: Mon Feb 19, 2024 3:26 am
by ESP_Sprite
Can you post your entire project?

Re: ESP32 S3 accessing the same variable from both cores

Posted: Mon Feb 19, 2024 11:38 am
by Slinisa
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.

Re: ESP32 S3 accessing the same variable from both cores

Posted: Mon Feb 19, 2024 1:39 pm
by ok-home
hi
volatile variables do not protect variables from date races
esp idf provides two possible protection options depending on application requirements
mutex and spinlock

Re: ESP32 S3 accessing the same variable from both cores

Posted: Tue Feb 20, 2024 9:54 pm
by MicroController
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.