Operating Systems | Concept of shared memory and critical section


While printing your document opened in Adobe Acrobat Reader, if you gave a same command for document opened in Microsoft Word! How will it be?

These are the real time situations where two processes competing together for same resources due to improper process synchronization.

An unstructured access approval to these resources may lead to a abnormal output or a breach in information security or even it may cause for data loss. In the above case which might be a bunch of over-written papers coming out of the printer connected to that system.




Shared Memory and Critical Section

Resources or memory spaces where different processes have access to read, write or update at same time are known as shared memory.

And the piece of program which tries to access the shared memory is known as Critical Section.
Representation of two processes accessing shared memory or shared resource

There are situations where an operating system need to handle multiple request from critical sections of various processes in a machine, in order to maintain data consistency in resources or shared memories and most importantly for a secure trade-off across various activities under that particular operating system.



  • Let a shares memory location var has to be accessed by two different processes P1 and P2 to increment and decrement respectively at an instant as shown.

At assembly level the code snippets for var+ + for P1 and var- - for P2 will be as follows.

HLL
var++

Assembly
1) MOV  var, WR0
2) INC    WR0
3) MOV  WR0, var
HLL
var- -

Assembly
1) MOV  var, WR1
2) DEC    WR1
3) MOV  WR1, var


In each of these cases

  • First instruction copies the value in var to some register.
  • Second instruction increases(for P1) or decreases(for P2) the value in the register.
  • Third one updates the var with new value in the register

Let P1.3 represent the third instruction of first process and see how various cases where an operating system with preemptive scheduling algorithm performs on var

Here final value of var is 5 or 4 or 6 depending on order of sequence of execution.

Getting an inconsistent or multiple final result on applying same operations is not a reliable result.

Such a situation where order of execution of instruction determines, the final result is called race condition in operating system.

The only way to resolve race condition is denial of other processes from accessing critical shared data the until completion of execution of current process over this shared memory.

In order to solve the data inconsistency with an efficient and to control the race which determines this inconsistent final result there are various methods of process synchronization will be discussed in upcoming articles.

Comments