10

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.

1
  • 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. Commented Aug 25, 2016 at 6:43

1 Answer 1

20

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Just to be clear: if the if condition evaluates to false, a loop runs entirely without OpenMP and not just with num_threads(1)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.