omp_workshare2.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /******************************************************************************
  2. * FILE: omp_workshare2.c
  3. * DESCRIPTION:
  4. * OpenMP Example - Sections Work-sharing - C/C++ Version
  5. * In this example, the OpenMP SECTION directive is used to assign
  6. * different array operations to threads that execute a SECTION. Each
  7. * thread receives its own copy of the result array to work with.
  8. * AUTHOR: Blaise Barney 5/99
  9. * LAST REVISED: 04/06/05
  10. ******************************************************************************/
  11. #include <omp.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #define N 50
  15. int main (int argc, char *argv[]) {
  16. int i, nthreads, tid;
  17. float a[N], b[N], c[N];
  18. /* Some initializations */
  19. for (i=0; i<N; i++)
  20. a[i] = b[i] = i * 1.0;
  21. #pragma omp parallel shared(a,b,nthreads) private(c,i,tid)
  22. {
  23. tid = omp_get_thread_num();
  24. if (tid == 0)
  25. {
  26. nthreads = omp_get_num_threads();
  27. printf("Number of threads = %d\n", nthreads);
  28. }
  29. printf("Thread %d starting...\n",tid);
  30. #pragma omp sections nowait
  31. {
  32. #pragma omp section
  33. {
  34. printf("Thread %d doing section 1\n",tid);
  35. for (i=0; i<N; i++)
  36. {
  37. c[i] = a[i] + b[i];
  38. printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
  39. }
  40. }
  41. #pragma omp section
  42. {
  43. printf("Thread %d doing section 2\n",tid);
  44. for (i=0; i<N; i++)
  45. {
  46. c[i] = a[i] * b[i];
  47. printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
  48. }
  49. }
  50. } /* end of sections */
  51. printf("Thread %d done.\n",tid);
  52. } /* end of parallel section */
  53. return 0;
  54. }