testsuite/libgomp.c/omp_matvec.c

Go to the documentation of this file.
00001 /******************************************************************************
00002 * OpenMP Example - Matrix-vector multiplication - C/C++ Version
00003 * FILE: omp_matvec.c
00004 * DESCRIPTION:
00005 *   This example multiplies all row i elements of matrix A with vector
00006 *   element b(i) and stores the summed products in vector c(i).  A total is
00007 *   maintained for the entire matrix.  Performed by using the OpenMP loop
00008 *   work-sharing construct.  The update of the shared global total is
00009 *   serialized by using the OpenMP critical directive.
00010 * SOURCE: Blaise Barney  5/99
00011 * LAST REVISED:
00012 ******************************************************************************/
00013 
00014 #include <omp.h>
00015 #include <stdio.h>
00016 #define SIZE 10
00017 
00018 
00019 main ()
00020 {
00021 
00022 float A[SIZE][SIZE], b[SIZE], c[SIZE], total;
00023 int i, j, tid;
00024 
00025 /* Initializations */
00026 total = 0.0;
00027 for (i=0; i < SIZE; i++)
00028   {
00029   for (j=0; j < SIZE; j++)
00030     A[i][j] = (j+1) * 1.0;
00031   b[i] = 1.0 * (i+1);
00032   c[i] = 0.0;
00033   }
00034 printf("\nStarting values of matrix A and vector b:\n");
00035 for (i=0; i < SIZE; i++)
00036   {
00037   printf("  A[%d]= ",i);
00038   for (j=0; j < SIZE; j++)
00039     printf("%.1f ",A[i][j]);
00040   printf("  b[%d]= %.1f\n",i,b[i]);
00041   }
00042 printf("\nResults by thread/row:\n");
00043 
00044 /* Create a team of threads and scope variables */
00045 #pragma omp parallel shared(A,b,c,total) private(tid,i)
00046   {
00047   tid = omp_get_thread_num();
00048 
00049 /* Loop work-sharing construct - distribute rows of matrix */
00050 #pragma omp for private(j)
00051   for (i=0; i < SIZE; i++)
00052     {
00053     for (j=0; j < SIZE; j++)
00054       c[i] += (A[i][j] * b[i]);
00055 
00056     /* Update and display of running total must be serialized */
00057     #pragma omp critical
00058       {
00059       total = total + c[i];
00060       printf("  thread %d did row %d\t c[%d]=%.2f\t",tid,i,i,c[i]);
00061       printf("Running total= %.2f\n",total);
00062       }
00063 
00064     }   /* end of parallel i loop */
00065 
00066   } /* end of parallel construct */
00067 
00068 printf("\nMatrix-vector total - sum of all c[] = %.2f\n\n",total);
00069 
00070   return 0;
00071 }
00072 

Generated on Fri Apr 5 05:38:10 2013 for Libgomp by  doxygen 1.4.7