Is this safe to do?

willywortel wrote on Wednesday, December 03, 2008:

I created a task that reads some hardware (ADC) value’s and save the data into for example variable X.

Then i have some other tasks like the display, the SD logbook and the USB that needs this variable X only to be read.

I think it is not safe to do this without a semaphore because at the time a task is reading, it could be possible that the variable gets set with new data.

So in my opinion a binary semaphore would be suffice. The semaphore would only be set when the variable gets a write.

But, does it matter that there are several readers tasks that could be interrupting each others read? So if for example the logbook and display both requests at the same time variable X by using the same variable getDataX();

davedoors wrote on Wednesday, December 03, 2008:

You describe a system where the variable X gets written to from one place, but read from many different places. When this is the case you only need to worry about mutual exclusion if writes to X are not atomic. For example, if you are running FreeRTOS on a 16 bit CPU and X is 32 bits then it will take two writes to update the value of X, and mutual exclusion is required to ensure nothing reads X between the first and second write. If however you are running FreeRTOS on a 32bit CPU and X is 8, 16 or 32 bits then it will only take one write to update the value of X and you do not need to worry about mutual exclusion.

If you do need mutual exclusion then you can use a simple critical section but only do this if reading X is done relatively infrequently.  Otherwise use a mutex.

zaphodbe wrote on Wednesday, December 03, 2008:

If the mutual exclusion which would be done by doing taskENTER_CRITICAL and taskEXIT_CRITICAL around the piece of code that is updating the X variable would not work.

I would do it with a single deep queue. 

I would have the variable X in the context of the tasks that are reading the value with a function that trys to read from the queue with a timeout of 0.  As such if the queue is empty no update to the variable X would occur, however if there is an update on the queue the X variable would be updated.  Either way the function would return the X variable.  All the reading tasks would call this function.

The task that is reading the ADC would put the value into the Queue instead of into X.

willywortel wrote on Thursday, December 04, 2008:

I used the mutex function from this OS. So if the variable needs an update, it first starts taking the mutex but this is only possible if all of the reading tasks are done.

During this update, the reading tasks will be put automatically in a suspend state until update is complete.

Thanks for the reply’s!