Friday, 1 January 2016

OpenMP Program for Array Addition

                    In this post, we will see sample OpenMP program for array addition (sum). It is the best example to understand how threads are created in OpenMP.
                    Here we will take two one-dimensional arrays, each of size of 5. We will create 5 threads. Each thread will be responsible for one addition operation.
                    In OpenMP, pre-defined preprecessor directive #pragma omp parallel is used to create threads. We can mention the number of threads to be created as a parameter to num_threads(). If you are not mentioning num_threads(), then the number of threads to be created is equal to number of cores in processor. Thread id can be obtained by using predefined function omp_get_thread_num().
                    Go through the following program:

Program: (arrayaddition.c)

void main()
int a[5]={1,2,3,4,5};
int b[5]={6,7,8,9,10};
int c[5];
int tid;

#pragma omp parallel num_threads(5)


How To Run:
To Compile:
gcc -fopenmp arrayaddition.c
(Note: -fopenmp is used to use OpenMP library)

To Run:


                         (Note: From above output, one thing you will come to know that all addition operations are running concurrently. Whichever thread finishes operation earlier, we are getting particular value of c[]. )

Next: OpenMP Program for Matrix Addition

Previous: How To Create Threads using OpenMP API

No comments:

Post a comment