Race Condition with Examples in OS
Each of the processes has some sharable resources and some non-shareable resources. The sharable resources can be shared among the cooperating processes. The non-cooperating processes don’t need to share the resources. Now, the question is what is the race condition. When we synchronize the processes and the synchronization is not proper then the race condition occurs. we can define the race condition as follows;
A race condition is a condition when there are many processes and every process shares the data with each other and accessing the data concurrently, and the output of execution depends on a particular sequence in which they share the data and access.
Now the question is how to prevent the race condition?
We can easily synchronize the processes to prevent the race condition. To prevent the race condition, we need to ensure that only one process can access the shared data at a time. This is the main reason why we need to synchronize the processes. we can describe the race condition as follows;
Example of race condition
Void bankAccount(double money)
shared= shared + money
Here we have used two variables. Suppose shared is a shared variable. Now let’s say that bankAccount function is called for its execution. The statements of this function will be executed in the following sequence;
- The previous value of the shared variable will be loaded into one of the registers of the CPU.
- The value of money variable will be loaded into some another register.
- The values of two variables will be stored in two registers and the result will be calculated.
- Now, assign the result to the variable share.
For example, there are two processes P1 and P2 and both P1 and P2 processes are willing to call the function bankAccount concurrently.
suppose P1 call the function of bank account by passing the parameters of the function and the value of the parameter is 200 and similarly, P2 call the function of the bankAccount by passing the value of the parameter as 100.
Now, let’s suppose that the previous value of the shared variable is 1100. in this example we are resuming that process P1 and P2 are executed on the different processors.
The result can be looks like;
- Process P1 loads 1100 into the CPU register
- P2 will load 1100 into its register.
- P1 will add 200 to its register then the result will be 1300
- The process P2 will add 100 its register and the calculated result will be 1200
- The process P1 will store 1400 in shared variable and the process P2 will store 1150 in a shared variable.