Simple way to use global variables with FreeRTOS

Hi,Is there any simple way besides enter and exit critical when use many global variables. if use FreeRTOS objs, i can not recept this:too much ram be used.

First, making a variable global doesn’t decrease how much space it takes, it just moves it from the task stack to the global space. It does make it perhaps easier to account for, and often makes the lack of memory clearer as you might get a link error rather than a stack overflow or out of memory run time error.

Second, if using a global variable to share information between tasks, you only need to protect things if the access is not inherently atomic, often the simple reading of a simple variable will naturally be atomic on the machine, and thus not need to be protected. Sometimes due to higher level synchronizations, you know that at this time there are no competing access, so you don’t need to protect the data (the other task generating the data has signal this task that it is done and now you turn to use it).

Sometimes the problem is just inherently complicated and needs a lot of memory, and it is useful to think about the problem and perhaps reorganize it to need less.

Without a better description of what you are trying to do, or what problem you are actually having, it is hard to give advice.

Thank you for reply,Mr RD.
in your “firsrt”,well I mean for example if I def
20 vaviables ,am i need to create 20 queues each to protect them when reading or writing with them?i think this is too expensive.i don,t think global variable take too much ram as you say,sorry not make it clear.
and i am not sure about your left words that is total right,but thanks for your advise.

First, your should plan some discipline on your sharing of data between tasks, and not just have it happen at random. If you do that, you will likely find that often a group of variables should really be treated as a single shared resource using a single mutex to protect them (you want the set in a consistent value together).

The other thing that you may see is that a given variable is used in isolation and can be accessed in an atomic way (the processor naturally will read/write the whole value in one CPU cycle), that means that this access doesn’t need to be protected, as the processor naturally does this.

Some other times, the section that needs atomic access that isn’t provide by the processor is very short, and you can provide the level of protection by the use of a critical section, of if a somewhat longer period, buy suspending the scheduler.

1 Like