taskYIELD() in a loop as best strategy?

Hi,
I have a loop inside which a flag is constantly monitored. Because the tick is 1ms and I am ok checking for that flag every few ms, I don’t want the execution to waste time for the rest of that tick period inside that loop when other taks could do more productive/important work.

Is taskYIELD() the best strategy? like this:

while (flag == 1)
{
    taskYIELD();
}
... rest of code

or perhaps putting a vTaskDelay of few ticks or maybe some other option?

Thank you :slight_smile:

Hi @Rik001, is the flag you’re polling being set to indicate/notify an event/state from another task?
In that case, it would be better to block this task until it receives the notification from the other task using the mechanism of FreeRTOS Task Notifications instead of periodically polling for the flag.

taskYIELD() likely doesn’t do what you want, unless your task is a priority 0 (i.e. IDLE Priority) task, as a yield will only let another task of your priority or higher run. (and only goes to a higher priority if you have disabled preemption, or it would have gone to that when it first became ready).

Thank you aws-archir and Richard,

@aws-archit, no, the flag is just a global variable that can be set by an INT. What would you suggest for this case as an elegant/correct solution?

@richard-damon, all the tasks are currently at the same priority. That is why I thought of that solution. But perhaps there are better ones?

Thank you :slight_smile:

All tasks being the same priority normally means that you didn’t need an RTOS.

Better would be to use a FreeRTOS operation. It could be an EventGroup, Semaphore or a direct-to-task notification depending on exactly what you want to do with it.

1 Like

well, it mostly depends on what “rest of code” does. If that’s a predictably bound computation, you can simply create a FreeRTOS timer that checks the flag and executes “rest of code” if flags is != 1. If that is a lengthy computation, however, you can employ a variation of your scheme, namely, a task that is normally suspended and woken via vTaskResume() by your timer routine if the flag is != 1. That’s fairly off-the-shelf-code.

Thank you RAc and Richard :slight_smile: