#include<stdio.h>
#include "shared.h"
#include "forkjoin.h"
#include "barrier.h"int main()
{
int *x, *y, nproc, pid, *imin, *imax, *bar, *xsave, step, npts, i;
int size;
int sh1, sh2, sh3, sh4, sh5, sh6;
printf("Enter the size of the array :: ");
scanf("%d",&size);
printf("Enter the total number of processes :: ");
scanf("%d", &nproc);
x=(int *)create_memory(2*size, &sh1);
y=(int *)create_memory(2*size, &sh6);
imin=(int *)create_memory(2*nproc, &sh2);
imax=(int *)create_memory(2*nproc, &sh3);
bar=(int *)create_memory(4*2, &sh4);
xsave=(int *)create_memory(2*nproc, &sh5);
barrier_init(bar, nproc);
npts = (size/nproc);
step = size%nproc;
for(i=0;i<size;i++)
{
x[i] = i+1;
y[i] = 1;
}
pid = create_process(&nproc);
if(step==0)
{
imin[pid]=pid*npts;
imax[pid]=imin[pid]+npts-1;
}
elseif(pid<step)
{
imin[pid]=pid*(npts+1);
imax[pid]=imin[pid]+npts;
}
else
{
imin[pid]=pid*npts+step;
imax[pid]=imin[pid]+npts-1;
}
xsave[pid]=x[imax[pid]+1];
barrier(bar);
for(i=imin[pid];i<imax[pid];i++)
x[i]=x[i+1] + y[i];
if(i!=size-1)
x[i] = xsave[pid] + y[i];
join_process(&nproc, &pid);
printf("\nThe resultant array is :: ");
for(i=0;i<size;i++)
printf("\n%d",x[i]);
cleanup_semaphore(&bar[3]);
cleanup_memory(&sh1);
cleanup_memory(&sh2);
cleanup_memory(&sh3);
cleanup_memory(&sh4);
cleanup_memory(&sh5);
cleanup_memory(&sh6);
printf("\n");
return 0;
}
/* OUTPUT */
Enter the size of the array :: 12
Enter the total number of processes :: 3
The resultant array is ::
3
4
5
6
7
8
9
10
11
12
13
12