Question concerning number of threads in OpenMP programme

Hello,

I am starting to learn parallel programming with OpenMP. I stumbled over an interesting tutorial: https://bisqwit.iki.fi/story/howto/openmp/

There is a hello world-example like this:

#pragma omp parallel
{
// Code inside this region runs in parallel.
printf("Hello!\n");
}

Is it nornally true that the number within the team of threads created by OpenMP equals the number of cores? So if I execute this programme on a single core computer, does it print "Hello!" exactly once?
Apparently.

You can override the default by setting environment variable OMP_NUM_THREADS.
(I did just test that with values 1 and 60 and my cores are something in between.)

The pragmas seem to allow a num_threads clause.

There might be a function to change number of threads (size of pool) at start of program so that you could use command line parameter rather than environment variable.
Before your pragma statement:
omp_set_num_threads( nThreads );

You can have more than one thread per core.



g++ -fopenmp -O3 -o pi.exe pi.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <ctime>
#include "omp.h"                                           // OpenMP
using namespace std;

int main()
{
   const int N = 100000000;

   for ( int nThreads = 1; nThreads <= 8; nThreads++ )
   {
      clock_t start = clock();
      double sum = 0.0, sign = 1;

      omp_set_num_threads( nThreads );                     // OpenMP
      #pragma omp parallel for reduction( + : sum )        // OpenMP
      for ( int i = 0; i < N; i++ )
      {
         sum += sign * 4.0 / ( 1.0 + 2.0 * i );
         sign = -sign;
      }

      clock_t end = clock();

      cout << "Threads: " << nThreads << "     Sum: " << sum << "     Time: " << (double)( end - start ) / CLOCKS_PER_SEC << " s\n";
   }
}

Last edited on
Thank you very much! My question was more or less inane.
Registered users can post here. Sign in or register to post.