Day 81 - Process Synchronization And Race Condition

This post was intended to be about how CPU scheduling works in Windows Operating System but that is for another day maybe but for today it will be about Process Synchronization and Race Condition.

Process Synchronization

Process synchronization deals with mechanisms to ensure the proper execution of all the process that share same logical address. Its basic purpose is to maintain data consistency. A cooperating process is a process that is affected or can be affected by another process executing in the same system.

Conxcurrently running processes without any sort of data protection scheme can manipulate data and produce an incorrect result. So we need to implement a mechanism to prevent this from happening by synchronizing processes. When more than two processes share and manupulate same data a Race Condition occurs.

Race Conditions

A race condition is a situation in which more than one process access and manipulate shared data at the same time. The final value of the shared data depends upon which process finishes at last. To prevent race conditions, processes running at the same time must be synchronized.

Consider the following procedure.

def deposit(amount):
  balance = balance + amount

Here we assume that the balance variable is shared by multiple processes. If two processes call the deposit() at the same time, something that you don't want to happen, can happen. The statement balance = balance + amount is implemented by the following sequence of instructions.

Load  Reg, balance    ; loads the previous balance in register
Add   Reg, amount     ; add the amount
Store Reg, balance    ; updates the calculated amount back in balance

Now lets suppose that two process, P1 and P2 call the function deposit() at the same time with P1 as deposit(10) and P2 as deposit(20). The initial balance is 100 and both processes run on different CPUs. It could happen like this:

P1 loads 100 into its register P2 loads 100 into its register P1 adds 10 to its register, giving 110 P2 adds 20 to its register, giving 120 P1 stores 110 in balance P2 stores 120 in balance

But that is not what we want. We wanted it to output 130. This bug is called a race condition and this kind of bug is very difficult to debug as it occurs rarely and may disappear when you are trying to debug it. The only way to prevent this is through very careful coding. Some systems contains constructs called synchronization primitives to prevent this bug from occuring.


zainscizainsci