Search code examples
c++openmp

OpenMp: Best way to create an array with size of the number of threads


specific i have to calculate pi parallel with OpenMp. I am just allowed using #omp parallel. So i wanted to create an array with the size of the number of processes and then calculating partially the sum parallel and then calculating the sums together. But it's unfortunately impossible to get the number of threads before the parallel version. So is the best way to create a very large array and initializing it with 0.0 and then calculating everything together or is there a better way? I would appreciate every answer. Thank you in advance!


Solution

  • Fortunately, it is not impossible to obtain the number of threads in advance. The OpenMP runtime does not simply launch a random number of threads without any control from both the programmer and the program user. On the contrary, it follows a well-defined mechanism to determine that number, which is described in detail in the OpenMP specification. Specifically, unless you've supplied a higher fixed number of threads with the num_threads, the number of threads OpenMP launches is limited by the value of the special internal control variable (ICV for short) called nthreads-var. The way to set this ICV is via the OMP_NUM_THREADS environment variable or via the omp_set_num_threads() call (the latter method overrides the former). The value of nthreads-var is accessible by calling omp_get_max_threads(). For other ICVs see the specification.

    All you need to do is call omp_get_max_threads() and use the return value as the size of your array, for the number of threads will not exceed that value, given that you aren't calling omp_set_num_threads() with a larger value afterwards and aren't applying the num_threads clause to the parallel construct.