Page 1 of 1

portENTER_CRITICAL explaination

Posted: Tue Oct 08, 2019 2:03 am
by gibson12345
Hey everyone,

trying to sort out a situation where I need to enter a critical section and trying to determine how the functionality within freeRTOS works. portENTER_CRITICAL is the function I get pointed to which points to vTaskEnterCritical. Both require a "mux" but I'm struggling to understand exactly what a "mux" is. Could someone offer some insight or explanation?

Cheers,
Gibson

Re: portENTER_CRITICAL explaination

Posted: Tue Oct 08, 2019 6:33 am
by ESP_Dazz
The mux used in portENTER_CRITICAL is actually a spinlock. A spinlock is required in order to prevent multiple CPUs from accessing the same resource concurrently (e.g. a variable, struct, or set of registers).

You can use a mutex spinlock as follows:

Code: Select all

#include <stdio.h>
static portMUX_TYPE my_mutex;
int my_resource = 0;

void app_main()
{
	vPortCPUInitializeMutex(&my_mutex);
	portENTER_CRITICAL(&my_mutex);
	//Access your resource here.
	my_resource++;
	portEXIT_CRITICAL(&my_mutex);
}
You can also initialize the mutex as such:

Code: Select all

static portMUX_TYPE my_mutex = portMUX_INITIALIZER_UNLOCKED;

Re: portENTER_CRITICAL explaination

Posted: Wed Sep 30, 2020 7:03 pm
by jhmluna
So, timer_spinlock_take and portENTER_CRITICAL do the same thing?

Re: portENTER_CRITICAL explaination

Posted: Fri Oct 02, 2020 12:16 pm
by ESP_Sprite
jhmluna wrote:
Wed Sep 30, 2020 7:03 pm
So, timer_spinlock_take and portENTER_CRITICAL do the same thing?
Not entirely in implementation, as the timer function uses a spinlock that is embedded in the timer object, while portENTER_CRITICAL needs you to provide your own spinlock. The effect is the same, however.