vPortMalloc() in Idle Task

michaeln32 wrote on Tuesday, March 06, 2018:

Hi,
Can I call vPortMalloc() and vPortFree() in Idle task ?

Thank you

Michael

richard_damon wrote on Tuesday, March 06, 2018:

The Idle task contains a call to vPortFree() it self so that must be safe. The key here is that vPortMalloc() and vPortFree() do not block. One implication of this is if you add a call to vPortMalloc() in a IdleHook, then your mallocFailHook must not block. (The IdleTask only does free, which can’t fail, so not an issue).

michaeln32 wrote on Wednesday, March 07, 2018:

Hi Richard
Can you please tell me what that means - vPortMalloc() and vPortFree() do not block.

Thank you

richard_damon wrote on Wednesday, March 07, 2018:

When you do something like take a semaphore or read from a queue, if the object isn’t ready, the task is ‘blocked’ and doesn’t continue running for a little time until the object is ready or the specified time out occures, and some other ready task will be run instead.

The idle task must never block, as if it does then there may not be any ready task to run, and the system will generally crash, as FreeRTOS assumes that there will always be a task to run, and the Idle task is there to provide such a task that is always able to run.

pvPortMalloc() and vPortFree() implement their exclusiom by stopping the scheduler when they enter the allocator, and that operation will always succeed (the currenly running task will continue to run until the scheduler is restarted, thus no need to ‘block’ and parrallel execution is prevented). This means that they meet the basic requirements for use in the Idle task. The one complication is that pvPortMalloc() might call the mallocFailHook if memory is exhausted. The IdleTask itself never calls pvPortMalloc(), so that isn’t an issue, if your Idle Hook does, then (since the Idle Hoo runs as part of the Idle Task), the mallocFailHook must not ‘block’ as then no task might be able to run. Stopping the whole system in a disable interrupts and infinite loop is not a ‘block’ for this purpose.