Mutex type to wait for all tasks to stop

ghost07
Posts: 36
Joined: Mon Oct 03, 2022 11:47 am

Mutex type to wait for all tasks to stop

Postby ghost07 » Thu Feb 01, 2024 5:15 pm

Hello, could you recommend me a mutex/semaphore use to wait for all tasks to stop?

Each task of interest has onStart, onResume and onStop handlers and main loop which waits for a Notification. If it receives a notification to stop, it calls its onStop handler.
There are particular situations where I want to wait for all tasks to finish their onStop() function before proceeding. Like before going to sleep, or after configuration is updated and I want to ensure all tasks are terminated before starting them again (e.g. tasks with sockets will have to wait for wifi connected event bit again and don't just start right away because wifi task haven't stopped yet and that bit wasn't cleared).

I was considering Counting Semaphore, but it seems it has reversed logic to what I need - it allows to "take" whenever there is at least one "give", but I need to wait until there is certain amount of "gives".

It seems the best blocking function for this purpose would be xEventGroupWaitBits() - with least unnecessary context switches.
But I can't figure out how many event bits I can use - in FreeRTOS docs it says there is 8 bits per group if configUSE_16_BIT_TICKS is set, 24 bits otherwise, and there will be about 15 tasks. I can't find configUSE_16_BIT_TICKS in sdkconfig, but I'm not sure if its not set somewhere else.

MicroController
Posts: 1725
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Mutex type to wait for all tasks to stop

Postby MicroController » Thu Feb 01, 2024 10:55 pm

The common approaches all require up to about N 'unnecessary' context switches to wait for N tasks because FreeRTOS doesn't have condition variables or the like. You can perform N 'takes' on a semaphore, or use N binary semaphores, or use task notifications which also allow you to use them as a counter.
I don't think it'd be worth the effort to try and save a bunch of context switches @ around 10-15us each, but you could turn down the priority of the waiting task so that it is is likely it won't even be eligible to execute until all the other tasks have ceased running.
16 bit ticks don't make sense on the 32-bit ESPs, so default is a 32-bit TickType_t, and I think you could only change that by modifying the FreeRTOS config header file - and that might well break some (IDF) code which expects TickType_t to be 32 bits, so 'accidentally' running with 16-bit is not going to happen.

Who is online

Users browsing this forum: VinayDand and 429 guests