The shared data problem occurs when several functions (or ISRs or tasks) share a variable. Shared data problem can arise in a system when another higher priority task finishes an operation and modifies the data or a variable before the completion of previous task operations.
Steps to eliminate shared data problem:
i) Use modifier volatile with declaration from variable that returns from interrupt. It warns the compiler that certain variables may modify.
ii) Use reentrant function with atomic instructions that needs its complete execution before it can be interrupted. This part is called critical section.
iii) Put a shared variable in a circular queue. The function that requires the value takes it from queue front. The function that inserts (writes) the value takes it at the queue back.
iv) Disable the interrupts before critical section starts executing and enable the interrupts on its completion. Even the high priority interrupts than the critical section gets disabled.
- Advantages: Semaphore functions have greater computational overhead than disabling of interrupt.
- Disadvantages: increase in interrupt latency period. Deadlines may be missed.
Application of semaphores in shared data problem
- Mutex is semaphore that provides at an instance two tasks mutually exclusive access ro resources and is used in solving shared data problem.
- Semaphores does not eliminate shared data problem completely.
- Drastic option of disabling interrupts in all critical sections by using semaphores cannot be done.
- When using semaphores, OS does not disable interrupt.
- Task switching flags can be used.