Callbacks and volatile variables

filo_gr
Posts: 109
Joined: Wed Jul 28, 2021 12:25 pm
Location: Italy

Callbacks and volatile variables

Postby filo_gr » Fri Oct 22, 2021 1:42 pm

Hi community, :D

I've searched in various websites to find the answer for the following questions, without finding it: does a callback need volatile variables (such as interrupts) when executed?
I know callbacks are called from events. Events could be triggered from interrupts. Since an interrupt is an asynchronuous event, also the following callback called by the interrupt should be an asynchronuous event.
If I have a global variable shared between my app_main() and a callback, I think it would be correct declare it as volatile.
However I noticed, inside the ESP-IDF examples, there aren't volatile variables in callbacks declared as volatile. I'm not referring to a specific example, I looked at various of them and there is the same situation.
Filippo

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

Re: Callbacks and volatile variables

Postby ESP_Sprite » Sat Oct 23, 2021 1:53 am

Even in interrupts, 'volatile' does not do what you think it does. The Linux kernel has a good bit of text about it. (Note that it mentions 'cpu_relax' as a compiler barrier that makes the C compiler assume the variable may have changed; this is true for all function calls, there's nothing special about the 'cpu_relax' function call in that respect. You can simply replace it with a vTaskDelay or vTaskYIELD or any other function call in ESP-IDF.)

filo_gr
Posts: 109
Joined: Wed Jul 28, 2021 12:25 pm
Location: Italy

Re: Callbacks and volatile variables

Postby filo_gr » Mon Oct 25, 2021 12:54 pm

ESP_Sprite wrote:
Sat Oct 23, 2021 1:53 am
Even in interrupts, 'volatile' does not do what you think it does. The Linux kernel has a good bit of text about it.
I read the article. Very useful because typical C programmers (as I am) may don't know how RTOS' kernel works.
So if I hypothetically have a callback related to the usb where I only change the status of a bool variable, such as this:

Code: Select all

void
usb_cdc_rx_callback (int itf, cdcacm_event_t * event)
{
    g_char_is_arrived = true;
    return;
}
And inside the app_main() I have the following part:

Code: Select all

if (g_char_is_arrived)
{
    g_char_is_arrived = false;
    (void) gpio_set_level(PIN_LED, 1);
}
Then the declaration must be:

Code: Select all

bool g_char_is_arrived;
without the volatile keyword. This is because the kernel handles the callbacks and the callback's variables are in a locked state and there's no need to suppress the optimization.

I hope I've understood in the right way :)
Filippo

Who is online

Users browsing this forum: Pedro Hugo PSC and 99 guests