barrier.h

 /*	
Practical Assignment : 3
Name    : Divyen K Patel Roll No:24 MCA-4
Program : 2
Header files for barrier
*/


void barrier_init(int *bar,int blocking_number)
{
bar[0] = blocking_number; // bar[0] for Number of Process to Block
bar[1]=0; // bar[1] for Number of Process
//        waiting at the barrier

bar[2]=0; // bar[2] for Processes remaining to release

// bar[2] = 0 till all process have not called the barrier and it is > 0
// when all processes have been blocked

spin_lock_init(&bar[3]); // bar[3] is locking variable
}


void barrier(int *bar)
{
// Private Variable Incemented is Set to 1
// When this Process Increment the internal barrier Counter bar[1]

int Incremented=0;

while(1)
{
spin_lock(&bar[3]);

// Check for non-blocked Process

if(Incremented==0 && bar[2] > 0)
{
spin_unlock(&bar[3]);
continue;
}



if(Incremented==0)
{
// Increment Internal Counter
bar[1]++;
Incremented=1;
}


if(bar[1] < bar[0] && bar[2]==0)
{
// Fewer than blocking number of Processes are at barrier
spin_unlock(&bar[3]);
continue;
}
else
{
// Release Mode
if(bar[2]==0) // Release First Process
{
bar[1]=0;
bar[2]=bar[0] - 1;
spin_unlock(&bar[3]);
return;
}
else // Release Remaining Process
{
bar[2]--;
spin_unlock(&bar[3]);
return;
}
}
}
}

Project Homepage: