I am trying to understand how mutexes are used (and why) in the context of esp32 critical sections. Googling hasn't led me to any clear answer. The examples I've found all seem to either allocate the mutex as a stack variable, or malloc it. Either way, its scope ends up being limited. For example:
Code: Select all
blah();
blah();
{
portMUX_TYPE mutex = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mutex);
access_to_some_common_resource();
portEXIT_CRITICAL(&mutex);
}
blah();
I don't understand how this does anything useful. The mutex object is a stack variable whose lifetime does not extend beyond the scope of this code. How can this possibly protect the shared common resource from other sections of code, without also sharing the semaphor / mutex object?
It seems to me that you would want to make the mutex object global, so that everyone who shares the common resource has to attempt to grab the same mutex object first. So that would imply making the thing global, and putting the definition of it in a shared .h file.
But I don't see any evidence anyone's doing it that way.
So what is it that I'm not understanding?
Thanks in advance!