Q. Write a pseudo code to find sum of two functions?
Let's write a pseudo code to find sum of two functions f(A) + f(B). In first algorithm we will not use locking.
Process A Process B
sum = 0 :
: :
fork B sum = sum+ f(B)
: :
sum = sum + f(A) end B
:
join B
:
end A
If process A executes statement sum = sum + f(A) in addition writes results in main memory followed by computation of sum by process B then we attain correct result however consider case when B executes statement sum = sum + f(B) before process A can write result in the main memory. Then sum comprises only f(B) that is incorrect. To avoid such variation we use locking.
Process A Process B
sum = 0 :
: :
: lock sum
fork B sum = sum + f(B)
: unlock sum
lock sum :
sum = sum + f(A) end B
unlock sum
:
join B
:
end A
In this case every time a process obtains sum variable it locks it sothat no other process can access that particular variable that guarantees consistency in results.