Quality RTOS & Embedded Software

 Real time embedded FreeRTOS RSS feed 
Quick Start Supported MCUs PDF Books Trace Tools Ecosystem TCP & FAT




Loading

Static variables and Tasks

Posted by michaeln32 on 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); } }


Static variables and Tasks

Posted by rtel on August 30, 2017

Is this a C question?


Static variables and Tasks

Posted by michaeln32 on August 30, 2017

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


Static variables and Tasks

Posted by rtel on 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.


Static variables and Tasks

Posted by michaeln32 on 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 ?


Static variables and Tasks

Posted by rtel on August 30, 2017

Yes.


[ Back to the top ]    [ About FreeRTOS ]    [ Sitemap ]    [ ]




Copyright (C) Amazon Web Services, Inc. or its affiliates. All rights reserved.

Latest News

FreeRTOS kernel V10 is available for immediate download. Now MIT licensed.


FreeRTOS Partners

ARM Connected RTOS partner for all ARM microcontroller cores

IAR Partner

Microchip Premier RTOS Partner

RTOS partner of NXP for all NXP ARM microcontrollers

STMicro RTOS partner supporting ARM7, ARM Cortex-M3, ARM Cortex-M4 and ARM Cortex-M0

Texas Instruments MCU Developer Network RTOS partner for ARM and MSP430 microcontrollers

OpenRTOS and SafeRTOS