A good system needs to make sure that race condition and deadlock can’t occur. In this post, let us learn about Race Condition and Deadlock.
What is a Race Condition?
When two processes are competing with each other causing data corruption.
As shown in the diagram, two persons are trying to deposit 1 dollar online into the same bank account. The initial amount is 17 dollar. Both the persons would be able to see $17 initially. Each of them tries to deposit $1, and the final amount is expected to be $19. But due to race conditions, the final amount in the bank is $18 instead of $19. This is also known as dirty read.
For example, if two processes/threads are trying to execute the following conditions simultaneously, they cause data corruption:
total = num1 + num2
total = num1 - num2
It is very common for the race conditions to go unnoticed during testing even after multiple tests and code reviews. But in production, there would be a lot of processes and threads working parallelly and compete for the same resources, and this problem would occur.
What is a Dead Lock?
When two processes are waiting for each other directly or indirectly, it is called deadlock.
This usually occurs when two processes are waiting for shared resources acquired by others. For example, If thread T1 acquired resource R1 and it also needs resource R2 for it to accomplish its task. But the resource R2 is acquired by thread T2 which is waiting for resource R1(which is acquired by T1).. Neither of them will be able to accomplish its task, as they keep waiting for the other resources they need.
As you can see in the second diagram, process 1 is waiting for process 2 and process 2 is waiting for process 3 to finish and process 3 is waiting for process 1 to finish. All these three processes would keep waiting and will never end. This is called deadlock.