user1488118 user1488118 - 3 months ago 37
C Question

Enable/disable OpenMP locally at runtime

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.

Answer

You can use num_threads to dynamically sepecify the number of threads.

int num = 2;
#pragma omp parallel for num_threads(num)
for (int i = 0; i < 12; ++i) {}

UPDATE

Thanks for @Harald 's reminding. I did some research on the effect of omp_set_num_threads, and found that omp_set_num_threads only set the default thread number for current thread. So you can safely call omp_set_num_threads to set the thread number in different threads.

void f1() {
    omp_set_num_threads(2);
    fprintf(stderr, "f1: thread num: %d\n", omp_get_max_threads());
    sleep(3);    // ensure f2 calls omp_set_num_threads
    fprintf(stderr, "f1: thread num: %d\n", omp_get_max_threads());
#pragma omp parallel
    {fprintf(stderr, "f1: %d, %d\n", omp_get_thread_num(), omp_get_num_threads());}
}

void f2() {
    omp_set_num_threads(4);
    fprintf(stderr, "f2: thread num: %d\n", omp_get_max_threads());
    sleep(3);    // ensure f1 calls omp_set_num_threads
    fprintf(stderr, "f2: thread num: %d\n", omp_get_max_threads());
#pragma omp parallel
    {fprintf(stderr, "f2: %d, %d\n", omp_get_thread_num(), omp_get_num_threads());}
}

int main() {
    thread t1(f1);
    thread t2(f2);
    t1.join();
    t2.join();
    return 0;
}

Output:

f1: thread num: 2
f2: thread num: 4
f1: thread num: 2
f2: thread num: 4
f1: 0, 2
f1: 1, 2
f2: 0, 4
f2: 2, 4
f2: 3, 4
f2: 1, 4