Void * is used to maintain state ... (C programming)

We are currently studying how to program AVR microcontrollers (Ansi C89 only). Part of the drivers included is the heading that is planning, i.e. launches tasks at different speeds. My question is related to a quote from the documentation:

"Each task must maintain its own state using static local variables."

What does this really mean? They seem to be passing void* functions to maintain state, but then not using it?

Looking at the code in the file I am compiling, this is what they mean:

 {.func = led_flash_task, .period = TASK_RATE / LED_TASK_RATE, .data = 0} /* Last term the pointer term */ 

There is a function that works with the above parameters in the array, however it only acts as a scheduler. Then the function led_flash_task is equal to

 static void led_flash_task (__unused__ void *data) { static uint8_t state = 0; led_set (LED1, state); /*Not reall important what this task is */ state = !state; /*Turn the LED on or off */ } 

And from the title

 #define __unused__ __attribute__ ((unused)) 

And is the void *data transition designed to maintain the state of the task? What is meant by this?

thanks for the help

+6
source share
4 answers

As can be seen from the __unused__ compiler macro, the parameter is not used. As a rule, this is done because the method must correspond to a certain signature (interrupt handler, new thread, etc.). Think of the pthread library case, where the signature is something like void * func (void * data). You can use or not use the data, and if the compiler does not complain, then sticking the __unused__ macro removes the warning, telling the compiler that you know what you are doing.

I also forgot about static variables, as was said in another answer, static variables do not change from a method call to a method call, so the variable is saved between calls, therefore the state is saved (only thread-safe in C ++ 11).

+5
source

data is not used in this function (hence __unused__). The state is stored in the state of a static variable, which will retain its value between calls. See Also What is the lifetime of a static variable in a C ++ function?

+2
source

From the documentation: unused This attribute bound to a variable means that the variable should probably not be used. GCC will not issue a warning for this variable.

+1
source

State must be maintained in a local static variable.

This means a variable declared inside a function with a static keyword:

 static uint8_t state = 0; 

in your example.

This has nothing to do with the parameter passed to the task, which is not used in your example.

+1
source

Source: https://habr.com/ru/post/898131/


All Articles