Disabling OpenMP

In my C ++ program, I would sometimes like to run its executable file, and sometimes without using OpenMP (i.e. multithreading or single-threaded). I consider either of the following two cases in which my code uses OpenMP:

(1) Suppose my code only has directives #include <omp.h>and OpenMP.

(2) Same as (1), and my code further calls OpenMP functions such as omp_get_thread_num().

To not have other code for another run, the only way to use some self-defined precompiler variable for protection is where does OpenMP appear in my code?

Thank you and welcome!

+3
source share
4 answers

, :

omp_set_num_threads(m_iUseableProcessors);

m_iUseableProcessors - , . , OpenMP. #ifdef , OpenMP .

+2

:

set OMP_NUM_THREADS=1

, OpenMP. OpenMP . . 1, 2, 3, 4 .. .

+9

include :

#ifdef _OPENMP_
#include<omp.h> 
#endif

, -fopenmp, openmp

+3

_OPENMP C99 _Pragma ( __pragma, ++ - . fooobar.com/questions/425265/...), #ifdef _OPENMP #endif, , , 3x O (1) O (n) OpenMP.

, OpenMP C99. ++ , , , ( __GNUC__, __clang__, __INTEL_COMPILER ..).

#ifndef PRAGMA_OPENMP_H
#define PRAGMA_OPENMP_H

#if defined(_OPENMP) && ( __STDC_VERSION__ >= 199901L )

#define PRAGMA(x) _Pragma(#x)

#define OMP_PARALLEL PRAGMA(omp parallel)
#define OMP_PARALLEL_FOR PRAGMA(omp parallel for schedule(static))
#define OMP_FOR PRAGMA(omp for schedule(static))

#define OMP_PARALLEL_FOR_COLLAPSE(n) PRAGMA(omp parallel for collapse(n) schedule(static))
#define OMP_PARALLEL_FOR_COLLAPSE2 OMP_PARALLEL_FOR_COLLAPSE(2)
#define OMP_PARALLEL_FOR_COLLAPSE3 OMP_PARALLEL_FOR_COLLAPSE(3)
#define OMP_PARALLEL_FOR_COLLAPSE4 OMP_PARALLEL_FOR_COLLAPSE(4)

#define OMP_PARALLEL_FOR_REDUCE_ADD(r) PRAGMA(omp parallel for reduction (+ : r) schedule(static))

#else

#warning No OpenMP, either because compiler does not understand OpenMP or C99 _Pragma.

#define OMP_PARALLEL
#define OMP_PARALLEL_FOR
#define OMP_FOR
#define OMP_PARALLEL_FOR_COLLAPSE(n)
#define OMP_PARALLEL_FOR_COLLAPSE2
#define OMP_PARALLEL_FOR_COLLAPSE3
#define OMP_PARALLEL_FOR_COLLAPSE4
#define OMP_PARALLEL_FOR_REDUCE_ADD(r)

#endif

#endif // PRAGMA_OPENMP_H
0

Source: https://habr.com/ru/post/1716493/


All Articles