Coordinated shutting down of tasks

When I vTaskDelete a task that is stuck in a function that might block for a long time, what happens exactly? Are the resources lost, since the task will never get any time slices again.

What is the best way to shut down a task in a coordinated manner such that it exits its loop and moves to suspend right before calling vTaskDelete?

With FreeRTOS, Tasks don’t “own” resources, but the program as a whole manages them.

The best way I know to eat a task to safely terminate, is to use a global variable that it checks, and when it sees it set, goes off to end itself (and normally best for it to vTaskDelete itself rather than some other task doing it). If it might be stuck in a long block, there is the Abort Delay function to immediately wake it up, so it can test the flag variable.

The other option is to have a message you can send it to tell it to end, and when it processes that message it does a clean termination of itself.

I will also admit, that most times I don’t find myself starting and stopping tasks as the system runs, almost always every task is started at the beginning and they “run” (though mostly in the “Blocked” state) until the system is turned off.


I see. Thanks, I think we have different approaches then. To give you some background:

I’m working on a CAN-adapter based on an ESP32. It talks a custom protocol via BLE’s L2CAP where you can open channels, send data, and close channels. The moment the first channel gets opened, the CAN subsystem gets initialized and the appropriate tasks are started. The moment the last channel gets closed, the CAN subsystem gets completely uninitialized and the tasks are cleaned up, including all IPC allocated by those tasks.

The adapter can also move to another operating mode, which is a WiFi/Automotive ENET bridge.

Both operating modes are completely independent from another and I want to shutdown all resources of mode A while mode B is active.

In terms of energy consumption (the adapter is powered through the OBD2 socket, hence the battery in the vehicle), it’s very important to consume as few as possible, because if your battery runs dry while you’re reprogramming an ECU, you can call the car tow service :slight_smile:

The point is that a task that is blocked consumes ZERO power. Unless you are short on RAM resources, there is no need to take down and then bring back up each system, and in fact, doing so is going to cost you power, as that takes processing.

1 Like