critical section or semaphores? to protect a large list of variables

seanbzd wrote on Sunday, June 21, 2015:

I have a large list of variables that can be read or written to by multiple tasks. One of the Task that updates some of these variables is triggered off(using semaphore take/give)of an interrupt when new data is available.
Option 1: Create a ReadVariable() and WriteVariable() functions that use a critical section to protect the variable and the only way to access the variable.
Option 2: Create a semaphore for “each” variable. Have multiple functions in a class that may be accessing these variables directly but uses the specific semaphore associated with that variable to read/write that variable. How performance/memory intesive is creating and using a semaphore because in this method, each variable has its own semaphore.

Any suggestions/advice? Thanks.

rtel wrote on Monday, June 22, 2015:

From the information you have provided I would not recommend creating a semaphore for a single variable - only if you need to update more than one variable at once without interruption from other tasks of interrupts (ie. variables must all be consistent with each other, rather than on an individual basis).

You could have a read_variable function that uses a critical section. Whether the write_variable function also needs a critical section depends on how the variable is updated. If the variables are just written to directly, then they probably don’t need a critical section - if on the other hand writing to a variable requires a read-modify-write operation (for example variable += 2; or variable++;) then that will need a critical section too.


richard_damon wrote on Monday, June 22, 2015:

A key thing to look at is how long does a task need “ownership” of the variables to do what is needed. If you can do the operation in a few operations (and the length of a “few” is dependent on how much slack you have in your required interrupt latency) then a critical section is a good way to go. If the time is a bit too long for a simple critical then a mutex (I would prefer it over a semaphore to add the priority inheritance) over the variables could make sense. If you have contention over different unrelated variables, then breaking things down into smaller groups might make sense (task1 & task2 need variables var1 and var2, while task3 & task4 need variables var3 & var4), you likely don’t need a mutex for EACH variable, but for variable groups.

Another observation. if the access to a variable is naturally atomic (the items are natural word sizes for the processor), and you aren’t concerned about inter-variable interactions (i.e. a change to var1 needs a change to var2), then reads likely do not need to be protected at all, and writes only if they are a read-modify-write with multiple writers. If there are inter-variable interactions then you definitely don’t want a mutex for a single variable, but for the cluster that is updated together.