Static variables and Tasks

michaeln32 wrote on Wednesday, August 30, 2017:

Hi
I wrote a code that includes global variable, static variable and local variable.

Can you please tell me if I wrote it in the right way ? I mean in the task safe way

Thanks

/////////////////////////////////The Code//////////////////////////////////////////

u32 GlobVariable = 0;
static u32 SttGlobVar = 0;

void Func(void)
{
static u32 SttLclVar = 0;

u32 locVar = 0;

locVar++;

Take_Sem();

SttLclVar++;

GlobVariable++;

SttGlobVar++;

Give_Sem();

}

void Task_1(void)
{
while(1)
{
Func();
vTaskDelay(100);
}
}

void Task_2(void)
{
while(1)
{
Func();
vTaskDelay(100);
}
}

rtel wrote on Wednesday, August 30, 2017:

Is this a C question?

michaeln32 wrote on Wednesday, August 30, 2017:

No, It’s RTOS question about using semaphores on static variables.

rtel wrote on Wednesday, August 30, 2017:

Anything that is global or static will get referenced by all tasks.
That is, there is only one copy of the variable, so anything that reads
or manipulates the variable will be reading/manipulating the same
variable. In your case you used a semaphore to ensure the only one task
accesses the variables at a time, but you are not checking the return
value of the semaphore before you access the variable. To use a
semaphore you would need to check the ‘take’ function’s return value
then only access the variable if the return value indicated the ‘take’
was successful.

If you are just accessing variables like this then it would be much more
efficient to use a critical section than a semaphore. The critical
region would only be a few assembly instructions.

michaeln32 wrote on Wednesday, August 30, 2017:

Thank you for your answer.

I understand that a local variable do get copied for each task and there is no reason to lock read/write operations on a local variable.

Am I right ?

rtel wrote on Wednesday, August 30, 2017:

Yes.