Text-only Table of Contents (frame/ no frame)
(7) Example of Parallelizing a Loop Previous Top Next

Example of Parallelizing A Loop

Example C ProgramExample Fortran Program
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N 100

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

int nthreads, tid, i;
float a[N], b[N], c[N];

/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i;


#pragma omp parallel shared(a,b,c,nthreads) 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
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 */

}

 
PROGRAM WORKSHARE1

INTEGER NTHREADS, TID, OMP_GET_NUM_THREADS,
+ OMP_GET_THREAD_NUM, N, I
PARAMETER (N=100)
REAL A(N), B(N), C(N)

! Some initializations
DO I = 1, N
A(I) = I
B(I) = A(I)
ENDDO

!$OMP PARALLEL SHARED(A,B,C) PRIVATE(I,TID)

TID = OMP_GET_THREAD_NUM()
IF (TID .EQ. 0) THEN
NTHREADS = OMP_GET_NUM_THREADS()
PRINT *, 'Number of threads =', NTHREADS
END IF
PRINT *, 'Thread',TID,' starting...'

!$OMP DO
DO I = 1, N
C(I) = A(I) + B(I)
WRITE(*,100) TID,I,C(I)
100 FORMAT(' Thread',I2,': C(',I3,')=',F8.2)
ENDDO
!$OMP END DO NOWAIT

PRINT *, 'Thread',TID,' done.'

!$OMP END PARALLEL

END







Previous Top Next


example_parallel_loop.src  last modified Mar 23, 2009 Introduction Table of Contents
(frame/no frame)
Printable
(single file)
© Dartmouth College