Is it possible to enable or disable OpenMP parallelisation at runtime? I have some code that should run in parallel under certain circumstances and not in parallel under different circumstances. At the same time, there are other computations in other threads that also use OpenMP and should always run in parallel. Is there a way to tell OpenMP not to parallelise in the current thread? I know of omp_set_num_threads, but I assume that globally sets the number of threads that OpenMP uses.
-
You shouldn't be combining OpenMP with other forms of threading as it goes beyond the scope of the standard and there is no guarantee that your program will work correctly with future versions of the respective OpenMP runtime.Hristo Iliev– Hristo Iliev2016-08-25 06:43:19 +00:00Commented Aug 25, 2016 at 6:43
Add a comment
|
1 Answer
An alternative you can use is to add an if condition to the #pragma omp constructs. These will skip the invocation to the OpenMP runtime calls derived from the pragmas whenever the condition is false.
Consider the following program that uses conditionals based on variables t and f (respectively true and false):
#include <omp.h>
#include <stdio.h>
int main (void)
{
int t = (0 == 0); // true value
int f = (1 == 0); // false value
#pragma omp parallel if (f)
{ printf ("FALSE: I am thread %d\n", omp_get_thread_num()); }
#pragma omp parallel if (t)
{ printf ("TRUE : I am thread %d\n", omp_get_thread_num()); }
return 0;
}
Its output is:
$ OMP_NUM_THREADS=4 ./test
FALSE: I am thread 0
TRUE : I am thread 0
TRUE : I am thread 1
TRUE : I am thread 3
TRUE : I am thread 2
2 Comments
bweber
Thanks, I think this is the perfect solution. I can just add a boolean variable to the pragma then, that specifies if the run should be parallelised or not.
user
Just to be clear: if the
if condition evaluates to false, a loop runs entirely without OpenMP and not just with num_threads(1)?