Consider the following FreeRTOS code snippet. What will be printed to the console?
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> TaskHandle_t xTaskHandle = NULL; void vTaskFunction(void *pvParameters) { printf("Task running\n"); vTaskDelete(NULL); } int main(void) { BaseType_t xReturned; xReturned = xTaskCreate(vTaskFunction, "Task1", 1000, NULL, 1, &xTaskHandle); if (xReturned == pdPASS && xTaskHandle != NULL) { printf("Task created successfully\n"); } else { printf("Task creation failed\n"); } return 0; }
Remember that xTaskCreate returns pdPASS if the task is created and the handle is set.
The code creates a task and stores its handle in xTaskHandle. Since creation succeeds, it prints "Task created successfully". The task itself prints "Task running" only when scheduled, but here the main function ends before the scheduler runs, so only the creation message appears.
In FreeRTOS, what is the purpose of a TaskHandle_t variable?
Think about how you can control or delete a specific task after creating it.
A TaskHandle_t is a pointer or reference to a task control block. It allows the program to manage the task later, such as deleting it or changing its priority.
Examine the code below. It tries to delete a task using its handle but causes a runtime error. What is the likely cause?
TaskHandle_t xTaskHandle = NULL;
void vTaskFunction(void *pvParameters) {
for (;;) {
// Task code
}
}
int main(void) {
xTaskCreate(vTaskFunction, "Task1", 1000, NULL, 1, &xTaskHandle);
vTaskDelete(xTaskHandle);
return 0;
}Consider when tasks actually start running and when handles become valid for deletion.
The task is created but the scheduler has not started yet, so the task is not running. Calling vTaskDelete on a task handle before the scheduler runs can cause undefined behavior or runtime errors.
Choose the correct code snippet that creates a task and stores its handle in xTaskHandle.
Remember the type of the last parameter and how to pass the address of a variable in C.
The last parameter of xTaskCreate expects a pointer to a TaskHandle_t variable. Passing &xTaskHandle correctly provides the address to store the created task's handle.
Given the code below, how many tasks are actively running after vTaskStartScheduler() is called?
#include "FreeRTOS.h" #include "task.h" TaskHandle_t xTask1Handle = NULL; TaskHandle_t xTask2Handle = NULL; void vTask1(void *pvParameters) { for (;;) {} } void vTask2(void *pvParameters) { for (;;) {} } int main(void) { xTaskCreate(vTask1, "Task1", 1000, NULL, 2, &xTask1Handle); xTaskCreate(vTask2, "Task2", 1000, NULL, 3, &xTask2Handle); vTaskDelete(xTask1Handle); vTaskStartScheduler(); return 0; }
Consider what happens when vTaskDelete is called before the scheduler starts.
Two tasks are created, but vTaskDelete(xTask1Handle) deletes the first task before the scheduler starts. So only the second task runs after vTaskStartScheduler().