omp_matvec.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /******************************************************************************
  2. * OpenMP Example - Matrix-vector multiplication - C/C++ Version
  3. * FILE: omp_matvec.c
  4. * DESCRIPTION:
  5. * This example multiplies all row i elements of matrix A with vector
  6. * element b(i) and stores the summed products in vector c(i). A total is
  7. * maintained for the entire matrix. Performed by using the OpenMP loop
  8. * work-sharing construct. The update of the shared global total is
  9. * serialized by using the OpenMP critical directive.
  10. * SOURCE: Blaise Barney 5/99
  11. * LAST REVISED:
  12. ******************************************************************************/
  13. #include <omp.h>
  14. #include <stdio.h>
  15. #define SIZE 10
  16. int
  17. main ()
  18. {
  19. float A[SIZE][SIZE], b[SIZE], c[SIZE], total;
  20. int i, j, tid;
  21. /* Initializations */
  22. total = 0.0;
  23. for (i=0; i < SIZE; i++)
  24. {
  25. for (j=0; j < SIZE; j++)
  26. A[i][j] = (j+1) * 1.0;
  27. b[i] = 1.0 * (i+1);
  28. c[i] = 0.0;
  29. }
  30. printf("\nStarting values of matrix A and vector b:\n");
  31. for (i=0; i < SIZE; i++)
  32. {
  33. printf(" A[%d]= ",i);
  34. for (j=0; j < SIZE; j++)
  35. printf("%.1f ",A[i][j]);
  36. printf(" b[%d]= %.1f\n",i,b[i]);
  37. }
  38. printf("\nResults by thread/row:\n");
  39. /* Create a team of threads and scope variables */
  40. #pragma omp parallel shared(A,b,c,total) private(tid,i)
  41. {
  42. tid = omp_get_thread_num();
  43. /* Loop work-sharing construct - distribute rows of matrix */
  44. #pragma omp for private(j)
  45. for (i=0; i < SIZE; i++)
  46. {
  47. for (j=0; j < SIZE; j++)
  48. c[i] += (A[i][j] * b[i]);
  49. /* Update and display of running total must be serialized */
  50. #pragma omp critical
  51. {
  52. total = total + c[i];
  53. printf(" thread %d did row %d\t c[%d]=%.2f\t",tid,i,i,c[i]);
  54. printf("Running total= %.2f\n",total);
  55. }
  56. } /* end of parallel i loop */
  57. } /* end of parallel construct */
  58. printf("\nMatrix-vector total - sum of all c[] = %.2f\n\n",total);
  59. return 0;
  60. }