Why do we need Synchronization in real life Applications



When two or more threads are accessing the same resource like a variable or a data structure, it may lead to inconsistent data or value. Such conditions that lead to inconsistency are known as race condition.
As an example let’s consider a variable count whose value is 7 at present. Consider two operations: count = count + 1 which is executed by thread1 and another operation count = count – 1 which is executed by thread2. Note that both threads are sharing the common variables count.

If both threads execute in parallel then the sequence of operation can be either:
count = count + 1
count = count – 1
or
count = count – 1
count = count + 1

In both sequences the end value of count will be 7 which is a consistent values. But often a single high-level language statement will be converted to multiple assembly language statement.

The count = count + 1 will be converted to following assembly language statement:
A: R1 = count
B: R1 = R1 + 1
C: count = R1
Statements are labelled as A, B and C for convenience. R1 is a CPU register. Similarly count = count – 1 will be converted to following assembly language statement:
D: R2 = count
E: R2 = R2 – 1
F: count = R2

Again statements are labelled as D, E and F for convenience. R2 is another CPU register. Statement A, B and C are executed by thread1 in parallel with statements D, E and F of thread2.

Let the value of count be 7. Now consider the following statement execution sequence: A, B, D, E, C, F as shown below:
A: R1 = count (R1 = 7)
B: R1 = R1 + 1 (R1 = 8)
D: R2 = count (R2 = 7)
E: R2 = R2 – 1 (R2 = 6)
C: count = R1 (count = 8)
F: count = R2 (count = 6)

End value of count after the above execution sequences is 6 which is an inconsistent value and the execution sequence can be considered as an example that led to race conditions.

To prevent race conditions we can use a mechanism known as synchronization.

Comments