cfreertos

Can xTaskCreate be preempted?


I understand that xTaskCreate doesn't invoke the task function but merely allocates the necessary scheduling resources and marks the task as ready to execute.

Given that FreeRTOS is a preemptive multitasking environment, do I have any guarantee that no task switch will occur at least before xTaskCreate writes the task handle to its output parameter? Consider the following code:

typedef struct {
   // .. some data the task needs to do its work
   TaskHandle_t task_handle;
} task_data_t;

task_data_t my_task_data;
xTaskCreate(task_fn, "", 1204, &my_task_data, 
    configMAX_PRIORITIES - 1, &my_task_data.task_handle);

Can I rely on my_task_data.task_handle being valid before task_fn begins, or should I use some additional synchronization to make sure task_fn doesn't try to access my_task_data.task_handle before it's valid?

Or is it 100% ridiculous of me to want the task to have its own storage of the task handle, when it can just call xTaskGetCurrentTaskHandle() if it ever needs it?


Solution

  • Given that FreeRTOS is a preemptive multitasking environment, do I have any guarantee that no task switch will occur at least before xTaskCreate writes the task handle to its output parameter?

    You can't guarantee that the no task switch will occur, but you can be sure that your task will not be put into the RUNNING state before all the initialization has finished.

    Can I rely on my_task_data.task_handle being valid before task_fn begins, or should I use some additional synchronization to make sure task_fn doesn't try to access my_task_data.task_handle before it's valid?

    Or is it 100% ridiculous of me to want the task to have its own storage of the task handle, when it can just call xTaskGetCurrentTaskHandle() if it ever needs it?

    You created XY's problem. You may need a task handle to do something with a task outside this task. If you want to access the handle in the task use xTaskGetCurrentTaskHandle().

    freeRTOS ports I use do not put the task into RUNNABLE state before assigning the parameters of xTaskCreate and your code will work correct, but there is no guarantee that another ports will behave the same.