Inter process Communication and Synchronization

We will discuss P1 and P2 in same computer, both trying to print. This situation is competition. So we have some shared memory and on which the communication will be made. But when we apply parallelism then some problems also arise.
Example

P1
{
  count--
}
And
P2
{
  count++
}
We will break the count statement into assembly language to make things more clear.
MOV count R0
DECR R0
MOV R0, count
MOV count R0
INC R0
MOV R0, count

Let’s see the execution sequences

Sequence Number 1

P2: 1,2,3      P1: 1,2,3
count is initialized with 5
Then after execution count will be: 5,6,5
Means first P2 will increase count from 5 to 6 and then P1 will decrease it to again 5.

Now we will see some interleaving of the executing instruction.
P2: 1,2 | P1: 1,2,3|P1: 3
Here “|” means execution is preempted.
So after executing instruction 1 and 2 process P2 has incremented the value of count but not stored it back in count and got preempted (execution was halted).
Then P1 came and executed instructions 1,2,3, here P1 has picked value 5 as P2 did not stored the value back, now P1 will decrement 5 and store 4 in the count variable.
So after P1 executes P2 will come and as its last instruction is pending, it will store the computed value = 6 in the count variable back.
So at last we see the value is wrong because it should be 5 after P2 followed by P1.


Sequence Number 2

P2: 1,2| P1: 1,2| P2: 3| P1: 3

Now if you execute this sequencing we will get the below anomaly.
When we execute P2’s 1,2 then count will become 6 but not stored, then P1’s 1, 2 will make count as 4 because P2 earlier has not stored the count value. And then P2’s 3rd instruction will make the count stored as 6 and then P1’s 3rd instruction will make the count = 4.
We could also see the set of values as below:
5 -> 6 -> 5 -> 4 -> 6 -> 4
So count will become 4 which is wrong. This kind of scenario is called Race Condition And the code which is common two both processes is called Critical Condition

Critical Section

It is the part of program where shared resources are accessed by processes and the resources are used in mutually exclusive fashion.
It is called critical because the order of execution matters tremendously here.


So as we can see that there is entry section and exit section in the above image, we have to go through first entry section and then Critical Section and then Exit section.