1.swap
2.test and set
these are hardware solutions for synchronization
for test and set
boolean TestandSet (boolean &target)
{
boolean rv=target;
target = TRUE;
return rv;
}
for process pi
do{
while(testandset(lock))
critical section
lock=false;
remainder section
}while(1);
here lock is boolean variable initial value of lock=false which implies critical section is free
now,
p1 starts its execution
p1 in while loop calls testandset(false)function
now target is also assigned to false and rv also assigned to false
in next instruction target changes to true which automatically changes lock to true
rv value which is false is returned
while(false) fails and p1 enters CS, now if p2 wants CS
p2 checks testandset(true), target value is changed to true
rv is assigned true, target is made as true then rv which true is returned
now while is true and it enters infinite while loop and p2 does not enter CS and
mutual exclusion satisfied.
so this condition will fail only if lock=false and then a process can enter into CS.
now, swap instruction
Void swap (boolean &a, boolean &b)
{
boolean temp=a;
a=b;
b=temp;
}
initial values:
boolean lock=false;
boolean key=true
for this consider code
do
{
key=true;
while(key==true;
swap(lock,key);
critical section
lock=false;
remainder section
}while(1);
process p1 is willing to enter CS, so it is at entry section. key is made true. or initial value of key = true.
Initial value of lock = false. while(key==true satisfies)
call swap(false,true). Initial value of lock = false. now, a=lock, b=key
temp=a=false
a=b=true
b=temp=false
now key and b, lock and a are connected/referenced
so value in a and b should be same as key and lock
so we change it respectively
control returns to while loop
now key is false, P1 enters CS now p2 wants to enter in cs so it makes key as true
now while key==true swap function is called
now at swap function. a and b made true
now swap(a,b) will retain the value as both have same values
now return to while loop. While condition satisfies and again enter swap function.
this continues till p1 makes lock=false
hence only one process in CS
mutual exclusion satisfied
in this way we use swap & test and set