Task 2.2 - Work Sharing This task explores the use of the for work-sharing const
ID: 3911455 • Letter: T
Question
Task 2.2 - Work Sharing
This task explores the use of the for work-sharing construct. The program provided that adds two vectors
together using a work-sharing approach to assign work to threads is given below:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNKSIZE 10
#define N 100
int main (int argc, char *argv[]) {
int nthreads, tid, i, chunk;
float a[N], b[N], c[N];
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0; // initialize arrays
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 ", nthreads);
}
printf("Thread %d starting... ",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 ",tid,i,c[i]);
}
} /* end of parallel section */
}
This program has an overall parallel region within which there is a work-sharing for construct. Compile and
execute the program. Depending upon the scheduling of work different threads might add elements of the
vector. It may be that one thread does all the work. Execute the program several times to see any different
thread scheduling. In the case that multiple threads are being used, observe how they may interleave.
Alter the code from dynamic scheduling to static scheduling and repeat. What are your conclusions?
Time of execution
Measure the execution time by instrumenting the code with the OpenMP routine omp_get_wtime() at the
beginning and end of the program, finding the difference in time.
Explanation / Answer
A work-sharing construct distributes the execution of the associated statement among the members of the team that encounter it. The work-sharing directives do not launch new threads, and there is no implied barrier on entry to a work-sharing construct.
The sequence of work-sharing constructs and barrier directives encountered must be the same for every thread in a team.
OpenMP defines the following work-sharing constructs, and these are described in the sections that follow:
for directive
sections directive
single directive
Work-sharing constructs divide the execution of code enclosed by the construct between threads in a team. For work-sharing to take place, the construct must be enclosed within the dynamic extent of a parallel region. For further information on work-sharing constructs, see the following directives:
DO END DO SECTIONS END SECTIONS WORKSHARE END WORKSHARE SINGLE END SINGLERelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.