kokonuts wrote: ↑Tue Feb 07, 2023 4:40 pm
Are you psychic? I already forgot today and made it a struct
then I came here to read your previous answer, just to find the new
Nah, I simply have lots of experience... you could say that by now I'm an expert at creating bugs in code
at some point you kinda get an intuition for what constructions are 'dangerous', as in they work but are easy to misunderstand by the next person (who might be yourself)
I made a new single task that reads messages from MessageBuffer and write the new incoming value to one member of the global struct, then in the same task read all the values. So now that there is only one task that deals with this global struct and I document that this global struct must not be accessed from another task, would I be safe?
It's hard to say. The issue with reading/writing a struct like this is that it can end up being written as it is read, meaning at the reader side you get a mix of both old and new data in the struct. If that's OK (e.g. the struct is a sort of ring buffer) it can work, in this particular case, in theory. But do know you're relying on deep hardware properties there like the memory consistency model in use; I'm decently sure Xtensa is TSO so it can't reorder writes, but something like the RVMO as used by RiscV might be able to. In that case, your code will work on an ESP32, but breaks if you port it to a multicore RiscV processor. (With reordering writes, what I mean is that core 0 might do a write to A and then to B, but because of optimizations to make everything go faster, core 1 might see them as a write to B and then to A.)
Generally, I'd advise to simply use spinlocks (taskENTER_CRITICAL/taskEXIT_CRITICAL in ESP-IDF) around accesses to a struct like this. It makes it immediately clear what you're trying to do (so no guesswork or possibilities for bugs if you rework it) and given you use the spinlocks properly, it's always safe regardless of architecture. The alternative is a deep dive into memory consistency models, and believe me, you don't want to do that every time you try to fix a simple bug.