Nothing Special   »   [go: up one dir, main page]

Algorithm

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Write a simple OpenMP program for vector addition (sum).

It is helpful to understand how threads


are created in OpenMP. To examine the above scenario, we are going to take two one-dimensional
arrays, each of size of 5. We will then create 5 threads. Each thread will be responsible for one
addition operation.

ALGORITHM:

1) Include all the required


header files
2) Define the number of
threads to use for vector
addition and size of the
array
3) Take input the value of
n.
4) Allocate space for the
array.
1) Include all the required
header files
2) Define the number of
threads to use for vector
addition and size of the
array
3) Take input the value of
n.
4) Allocate space for the
array.
1) Include all the required
header files
2) Define the number of
threads to use for vector
addition and size of the
array
3) Take input the value of
n.
4) Allocate space for the
array.
1) Include all the required header files
2) Define the number of threads to use for vector addition and size of the array
3) Take input the value of n.
4) Allocate space for the array.
5) Initialize arrays a and b with consecutive integer values.
6) Determine how many elements each process will work on.
7) Print output.
8) Clean up the memory
OpenMP is a vector addition algorithm that can be used to add two or more vectors together.The
algorithm works by iterating through each element of the input vectors and adding them together
element-wise.This creates a new vector with the same number of elements as the input vectors,
where each element is the sum of the corresponding elements from the input vectors.The algorithm
starts by initializing an empty vector to store the sum of the input vectors.The algorithm then loops
through each element of the input vectors, adding the corresponding elements together element-
wise and storing the result in the corresponding element of the sum vector.The loop continues until
all elements of the input vectors have been processed. Here is the pseudo-code for the OpenM
vector addition algorithm:

Input: Vector A, Vector B

Output: Vector C (sum of A and B)

C = []

for i in range(len(A)):

C.append(A[i] + B[i])

return C

SOURCE CODE:

#include <stdlib.h>

#include <stdio.h>
#include <omp.h>

#define ARRAY_SIZE 8

#define NUM_THREADS 4

int main (int argc, char *argv[])

int * a;

int * b;

int * c;

int n = ARRAY_SIZE;

int n_per_thread;

int total_threads = NUM_THREADS;

int i;

a = (int *) malloc(sizeof(int)*n);

b = (int *) malloc(sizeof(int)*n);

c = (int *) malloc(sizeof(int)*n);

for(i=0; i<n; i++)

a[i] = i;

for(i=0; i<n; i++)

b[i] = i;

omp_set_num_threads(total_threads);

n_per_thread = n/total_threads;

#pragma omp parallel for shared(a, b, c) private(i) schedule(static, n_per_thread)

for(i=0; i<n; i++)

{
c[i] = a[i]+b[i];

printf("Thread %d works on element%d\n", omp_get_thread_num(), i);

printf("\n");

printf("i\ta[i]\t+\tb[i]\t=\tc[i]\n");

for(i=0; i<n; i++)

printf("%d\t%d\t\t%d\t\t%d\n", i, a[i], b[i], c[i]);

free(a);

free(b);

free(c);

return 0;

OUTPUT:

RESULTS:

The maximum sum of two vectors is obtained when the two vectors are directed in the same
direction. Hence an Open MP program for vector addition is demonstrated.
SCENARIO – II

Write a simple OpenMP program for performing dot product. It is helpful to understand how threads
can be executed in parallel to sequentially check each element of the list for the target value until a
match is found or until all the elements have been searched. Note: In OpenMP, to parallelize the for
loop, the openMP directive is: #pragma omp parallel for.

ALGORITHM:

1) Include all the required header files.

2) Declare various variables.

3)Take size as input from the user.

4) Assign storage for dot product vectors. Next, we will initialize dot product vectors.

5) Initialize global sum.

6) Performing the dot product in an OpenMP parallel region for loop with a sum reduction for
illustration purposes.

7) Each thread will keep track of its partial sum.

8) Print the output.

The OpenM dot product algorithm is a method for calculating the dot product of two vectors.The
dot product is a scalar value that is calculated by multiplying the corresponding elements of the two
input vectors and then summing the results. The dot product is often used in linear algebra and
physics to represent the angle between two vectors, or to calculate the projection of one vector
onto another. The OpenMp dot product algorithm starts by initializing a variable to store the dot
product, and then loops through each element of the input vectors, multiplying the corresponding
elements together and adding the result to the dot product variable. Here is the pseudo-code for the
OpenMp dot product algorithm:

Input: Vector A, Vector B

Output: Scalar dot_product

dot_product = 0

for i in range(len(A)):

dot_product += A[i] * B[i]

return dot_product

It's important to note that the algorithm assumes that the input vectors are of the same length,
otherwise, it will fail. To handle vectors of different length, it's necessary to check if the vectors have
the same length, and if they don't, use the length of the smallest vector or use zero-padding to make
all vectors the same length before calculating the dot product.

The dot product of two vectors can also be calculated using matrix multiplication, where thefirst
vector is represented as a row vector and the second vector is represented as a column vector.

SOURCE CODE:
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <time.h>

#include <math.h>

#include <omp.h>

#define SIZE 10

int main (int argc, char *argv[])

float u[SIZE], v[SIZE], dp,dpp;

int i, j, tid;

dp=0.0;

for(i=0;i<SIZE;i++)

u[i]=1.0*(i+1);

v[i]=1.0*(i+2);

printf("\n values of u and v:\n");

for (i=0;i<SIZE;i++){

printf(" u[%d]= %.1f\t v[%d]= %.1f\n",i,u[i],i,v[i]);

#pragma omp parallel shared(u,v,dp,dpp) private (tid,i)

tid=omp_get_thread_num();

#pragma omp for private (i)

for(i=0;i<SIZE;i++){

dpp+=u[i]*v[i];
printf("thread: %d\n", tid);

#pragma omp critical

dp=dpp;

printf("thread %d\n",tid);

printf("\n dot product is %f\n",dp);

OUTPUT :

RESULTS:
Hence an open MP program for dot product is demonstrated. In conclusion, OpenMP is a simple and
efficient algorithm for calculating the dot product of two vectors. It's easy to understand and
implement, making it a good choice for many applications that require dot product calculation.

SCENARIO – III

Write a simple openMP program to demonstrate the sharing of a loop iteration by number of
threads . You can have a chunk size of 10 .

ALGORITHM

1) Include all required header files.

2) Define chunk size.

3) A parallel do/for loop divides up the iterations of the loop between threads.

4) There is a synchronization point at the end of the loop: all threads must finish their iterations
before any thread can proceed.

5) If the loop gives the same answers, if it is run in reverse order, then it is almost certainly parallel.

6) Print final output.

In this algorithm, we first specify the number of iterations for the loop using the variable "n".Then,
we use the OpenMP "parallel" directive to specify that the loop should be shared among threads.
Within the parallel block, we use the "private" clause to specify that each thread should have its own
copy of the "tid" variable, which stores the thread ID. We also use the "omp_get_thread_num()"
function to get the current thread ID and the "omp_get_num_threads()" function to get the total
number of threads.Next, we use the OpenMP "for" directive to divide the loop iteration among the
threads.Within the for loop, each thread will execute a portion of the loop and will print its thread ID
and the iteration number it is currently executing.

SOURCE CODE:

#include <omp.h>

#include <stdio.h>

#include <stdlib.h>

#define CHUNKSIZE 10

#define N 10

int main (int argc, char *argv[])

int nthreads, tid, i, chunk;

float a[N], b[N], c[N];


/* Some initializations */

for (i=0; i < N; i++)

a[i] = b[i] = i * 1.0;

chunk = CHUNKSIZE;

#pragma omp parallel shared(a,b,c,nthreads,chunk) private(i,tid)

tid = omp_get_thread_num();

if (tid == 0)

nthreads = omp_get_num_threads();

printf("Number of threads = %d\n", nthreads);

printf("Thread %d starting...\n",tid);

#pragma omp for schedule(dynamic,chunk)


for (i=0; i<N; i++)

c[i] = a[i] + b[i];

printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);

} /* end of parallel section */

OUTPUT:

RESULTS:
This algorithm demonstrates how OpenMP can be used to share loop iterations among multiple
threads, allowing for more efficient parallel processing. The output of this program will vary
depending on the number of threads and the specific implementation, but it will show that the
iterations are shared among the threads.

SCENARIO – IV

Write a open MP program to demonstrate the sharing of works of a section using threads. You can
perform arithmetic operations on the one dimensional array and this section load can be shared by
the threads.

ALGORITHM

1) Include all required header files.

2) Initialize

3) Allows separate blocks of code to be executed in parallel (e.g. several independent subroutines)

4) There is a synchronization point at the end of the blocks: all threads must finish their blocks
before any thread can proceed.

5) Print output.

SOURCE CODE:

#include <omp.h>

#include <stdlib.h>

#include <stdio.h>

#define SIZE 10

int main (int argc , char *argv[])

{ int i, nThreads, thread_id;

float w[SIZE], x[SIZE], y[SIZE], z[SIZE];

for (i=0; i<SIZE; i++)

w[i] = i * 1.5;

x[i] = i + 22.35;

y[i] = 0.0;

z[i] = 0.0;

#pragma omp parallel shared(w,x,y,z,nThreads)

private(i,thread_id)
{

thread_id = omp_get_thread_num();

if (thread_id == 0)

nThreads = omp_get_num_threads();

printf("Number of Threads = %d\n", nThreads);

printf("Thread %d starts...\n",thread_id);

#pragma omp sections nowait

#pragma omp section

{ printf("Thread %d doing section 1\n",thread_id);

for (i=0; i<SIZE; i++)

y[i] = w[i] + x[i];

printf("Thread %d: c[%d]= %f\n",thread_id,i,y[i]);

#pragma omp section

printf("Thread %d doing section 2\n",thread_id);

for (i=0; i<SIZE; i++)

{ z[i] = w[i] * x[i];

printf("Thread %d: d[%d]= %f\n",thread_id,i,z[i]);

printf("Thread %d done\n",thread_id); } }

OUTPUT:
RESULTS:
This algorithm demonstrates how OpenMP can be used to share work among multiple threads,
allowing for more efficient parallel processing. The output of this program will vary depending on
the number of threads and the specific implementation, but it will show that the work is shared
among the threads.

You might also like