开发者

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 pa开发者_开发知识库rameters 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


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).


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?


From the documentation: unused This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.


The state must be maintained in a local static variable.

That means a variable declared inside the function with the static keyword:

static uint8_t state = 0;

in your example.

This has nothing to do with the parameter passed into the task, which in your example doesn't get used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜