C Programming Blog

 
 
 
#include <stdio.h>
#include \"headfork.h\"
#include \"headshr.h\"

main()
{
    int i,id,n,nprc,v1[10],v2[10],shmid;
    int *final,sum=0;

    final=(int *)shared(sizeof(int)*4,&shmid);

    printf(\"Enter the limit of vector: \");
    scanf(\"%d\",&n);

    printf(\"\\nEnter the elements of vector1 : \");
    for(i=0;i<n;i++)
    {
        printf(\"\\nv1[%d] : \",i);
        scanf(\"%d\",&v1[i]);
    }

    printf(\"\\nEnter the elements of vector2 : \");
    for(i=0;i<n;i++)
    {
        printf(\"\\nv2[%d] : \",i);
        scanf(\"%d\",&v2[i]);
    }

    printf(\"\\nEnter the no.of proc: \");
    scanf(\"%d\",&nprc);

    id=p_fork(nprc);
    *(final+id)=0;

    for(i=id;i<n;i+=nprc)
    {
        *(final+id)=*(final+id) + (v1[i] * v2[i]);
    }

    p_join(nprc,id);

    for(i=0;i<nprc;i++)
        sum=sum + *(final+i);
    printf(\"\\nFinal sum of mul of 2 vectors are: %d\",sum);
}


OUTPUT

knoppix@ttyp0[pp]$ vi vec_mul_sum_lps.c
knoppix@ttyp0[pp]$ cc vec_mul_sum_lps.c
knoppix@ttyp0[pp]$ ./a.out
Enter the limit of vector: 5

Enter the elements of vector1 :
v1[0] : 2
v1[1] : 3
v1[2] : 1
v1[3] : 5
v1[4] : 4

Enter the elements of vector2 :
v2[0] : 1
v2[1] : 2
v2[2] : 3
v2[3] : 4
v2[4] : 5

Enter the no.of proc: 3

Final sum of mul of 2 vectors are: 51