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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With