# include <stdio.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"// included in attachment
# include "sharedlib.h"
# include "spinlock.h"
# define arrSize 10
int main()
{
int arr[arrSize]; // Arrayint iCount; // Counter Variableint *sum,*index,*lock; // Shared Variablesint shmidsum,shmidindex,shmidlock; // ShmID's For 3 Shared Variables int i; // For Storing Index Value in Processesint id; // To Store ID of the Processesint nproc=5; // Number of Processesint parsum;
/* Set Values in an Array */
for(iCount=0;iCount<arrSize;iCount++)
{
arr[iCount]=iCount+1;
}
sum=(int*)sshared(sizeof(int),&shmidsum);
index=(int*)sshared(sizeof(int),&shmidindex);
lock=(int*)sshared(sizeof(int),&shmidlock);
*sum=0;
*index=0;
spin_lock_init(lock);
id=process_fork(nproc);
parsum=0;
while(1)
{
spin_lock(lock);
// Critical Region
i=*index;
*index=*index + 1;
spin_unlock(lock);
if(i>=arrSize)
{
break; // Exit the While Loop When// Becomes > arrSize
}
parsum=parsum + arr[i];
}
spin_lock(lock);
// Critical Region
*sum=*sum + parsum;
spin_unlock(lock);
printf("\nPartial Sum of Process:%d is %d",id,parsum);
process_join(nproc,id);
printf("\n Final Sum is : %d\n", *sum);
// Cleaning Shared Memory
cleanup_memory(&shmidindex);
cleanup_memory(&shmidsum);
cleanup_memory(&shmidlock);
return 0;
}
/* Output
[divyen@localhost pp-tw2]$ ./Prog02
Partial Sum of Process:1 is 55
Partial Sum of Process:2 is 0
Partial Sum of Process:3 is 0
Partial Sum of Process:4 is 0
Partial Sum of Process:0 is 0
Final Sum is : 55
*/