# Program to calculate average of the elements of an array and then the average deviation using Race condition) ```# include <stdio.h>
# include <math.h>
# include \"/usr/include/sys/types.h\"
# include \"/usr/include/sys/shm.h\"
# include \"/usr/include/sys/ipc.h\"
# include \"/usr/include/sys/sem.h\"
# include \"forkjoin.h\"
# include \"sharedlib.h\"
# include \"spinlock.h\"

int main()
{
int arr;
int arrSize;        //Size of array
int iCount;        //Counter Variable
int id;            //Process ID
int nProc=3;        //number of Processes
float sum=0;

float *deviation,*avg;  // Shared Variables
int *lock;        // Shared Variable for Spinlock

int shmidavg,shmidlock,shmiddeviation;    // Shmid for Shared Variables

printf(\"Enter the Size of an Array :\");
scanf(\"%d\",&arrSize);

for(iCount=0;iCount<arrSize;iCount++)
{
printf(\"Enter arr[%d] :\",iCount);
scanf(\"%d\",&arr[iCount]);
}

/* Allocate Shared memory */
avg=(float*)sshared(sizeof(float),&shmidavg);
deviation=(float*)sshared(sizeof(float),&shmiddeviation);
lock=(int*)sshared(sizeof(int),&shmidlock);

spin_lock_init(lock);        // Spin Lock Initialization
*avg=0;

id=process_fork(nProc);        // Forking Processes

/* Partial Sum using Loop Spliting */
for(iCount=id;iCount<arrSize;iCount=iCount+nProc)
{
sum = sum + arr[iCount];
}

spin_lock(lock);
/* Critical Region */
*avg = *avg + ( sum /arrSize);    // Calculate Average from Partial Sums
spin_unlock(lock);

/*
---------------------------------------------------------------------------
Barrier Should be here, So that all Processes have to wait until Final
Average is Calculated.
---------------------------------------------------------------------------
*/

sum=0;
/* Calculate Sum(Xi - Mean) Using Loop Spliting */
for(iCount=id;iCount<arrSize;iCount=iCount+nProc)
{
sum = sum + pow(((float)arr[iCount] - *avg),2);
}

spin_lock(lock);
/* Critical Region */
*deviation = *deviation + (sum / arrSize-1); // Calculate Final Deviation
spin_unlock(lock);

process_join(nProc,id);        // Joining the Process

*deviation=sqrt(*deviation);
printf(\"Deviation : %f\\n\",*deviation);

/* Cleaning the Shared Region */
cleanup_memory(&shmidavg);
cleanup_memory(&shmidlock);
cleanup_memory(&shmiddeviation);
return 0;
}
```