Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A void* being used to maintain state... (C programming)

Currently we are learning how to program AVR micro-controllers (Ansi C89 standard only). Part of the included drivers is a header that deals with scheduling ie running tasks at different rates. My question is to do with a quote from the documentation:

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

What does that mean really? They seem to pass a void* to the function to maintain the state but then do not use it?

Looking at the code in the file I gather 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 runs with the above parameters in an array however, it only acts as a scheduler. Then the function led_flash_task is

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 header

#define  __unused__ __attribute__ ((unused))

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

Thank-you for your help

like image 857
Lhh92 Avatar asked Sep 27 '11 07:09

Lhh92


2 Answers

As you can see from the __unused__ compiler macro the parameter is unused. Typically this is done because the method needs to match a certain signature (interrupt handler, new thread, etc...) Think of the case of the pthread library where the signature is something like void *func(void *data). You may or may not use the data and if you don't the compiler complains so sticking the __unused__ macro removes the warning by telling the compiler you know what you're doing.

Also forgot about static variables as was said in the other answer static variables don't change from method call to method call so the variable is preserved between calls therefore preserving state (only thread-safe in C++11).

like image 94
Jesus Ramos Avatar answered Sep 20 '22 11:09

Jesus Ramos


data is unused in that function (hence the __unused__). State is kept in the static variable state, which will keep its value between calls. See also What is the lifetime of a static variable in a C++ function?

like image 20
jakber Avatar answered Sep 19 '22 11:09

jakber