C Programming Tutorial

 
 
 
 

Image

/*    
    Sum of the elements of the array using self scheduling
*/

# 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\"
# include \"sharedlib.h\"
# include \"spinlock.h\"
# define arrSize 10

int main()
{
    int arr[arrSize];            // Array
    int iCount;                // Counter Variable

    int *sum,*index,*lock;          // Shared Variables
    int shmidsum,shmidindex,shmidlock;  // ShmID\'s For 3 Shared Variables        
    int i;                    // For Storing Index Value in Processes

    int id;                    // To Store ID of the Processes
    int nproc=5;                // Number of Processes
    int 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;    
}

 
 
Didn't find what you were looking for? Find more on Program to do sum of the elements of the array using self scheduling