I ran across a situation recently where thread local storage seemed to be a good solution.
But I couldnt help but wonder why the documentation for the get/set functions says “This function is intended for advanced users only”.
My use case is in relation to a watchdog poke function - Ive implemented a generic set of give/take functions for a particular mutex, and while waiting to take that mutex I can sit in a loop with a per-iteration timeout after which I poke a watchdog function with a particular value to let the watchdog know the task is still alive. Storing the value to poke to the watchdog seemed rather convenient in thread local storage, as this can then be referenced by the mutex code based on the active TCB and I dont need to worry about passing it around as an argument.
Is anyone able to expand on the above mentioned note? Have I walked into some kind of potential trap?
Is the value same for all tasks or is it different? The thing to be careful about is - if you allocate a memory and store the pointer in TLS, you need to free it (just deleting the task is not enough).
I do not think so but there may be other solutions to the same problem (like you mentioned about passing the value as parameter).
What is the problem in doing that?
Hi Gaurav. The value is unique per task, so that I can check that all expected tasks have checked in.
No additional memory is allocated, I just store the value directly in the TLS.
The problem I had is that there are some system functions have I have had to implement, such as settimeofday() and gettimeofday() - these are supplied as blank implementations with the compiler and I have to implement them specifically for my application.
Inside those functions I need to interact with an RTC via SPI, but there is also a temperature sensor on the same SPI bus that another task interacts with.
So in any code that attempts to take the SPI mutex I can use the value from the TLS to poke the watchdog if I ever have to wait long enough for the take operation to timeout, without needing to e.g. modify the signature of a system function.
Im never interacting with the SPI devices outside of a FreeRTOS task, so I dont believe there is any risk in doing it this way?
Ok great. So on the original question about the whole “for advanced users” note, I suppose this is more of a suggestion to take a step back and carefully consider what you are doing with values in the TLS?
Otherwise, if treated properly, there are no particular consequences from using it?