Parallel Processing Tutorial 3
1) write a program to find sum of 10
element of any array using shared
memory.
#include<stdio.h>
#include "head.h"
int main()
{
int
id,i,shmid,sum=0,sum1=0,*sum2,a[10];
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
sum2=sharem(4,&shmid);
*sum2=0;
id=process_fork(2);
if(id==0)
{
for(i=0;i<10;i=i+2)
{
sum1+=a[i];
}
}
else
{
for(i=1;i<=10;i=i+2)
{
*sum2+=a[i];
}
}
process_join(id,2);
sum=sum1+*sum2;
printf("sum=%d\n",sum);
shmdt((void *)sum2);
shmctl(shmid,IPC_RMID,NULL);
}
OUTPUT
:
[08ce55@linux
~]$ vim tuto2.c
[08ce55@linux
~]$ gcc tuto2.c
[08ce55@linux
~]$ ./a.out
1
2
3
4
5
6
7
8
9
10
id=55