在运行时本地启用/禁用OpenMP

Enable/disable OpenMP locally at runtime

本文关键字:禁用 OpenMP 启用 运行时      更新时间:2023-10-16

是否可以在运行时启用或禁用OpenMP并行化?我有一些代码应该在某些情况下并行运行,而不是在其他情况下并行运行。同时,其他线程中的其他计算也使用OpenMP,并且应该始终并行运行。有没有办法告诉OpenMP不要在当前线程并行?我知道omp_set_num_threads,但我假设全局设置OpenMP使用的线程数。

您可以使用的另一种选择是在#pragma omp结构中添加if条件。当条件为false时,将跳过对从pragmas派生的OpenMP运行时调用的调用。

考虑以下基于变量tf(分别为真和假)使用条件的程序:

#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 %dn", omp_get_thread_num()); }
    #pragma omp parallel if (t)
    { printf ("TRUE : I am thread %dn", omp_get_thread_num()); }
    return 0;
}

输出为:

$ 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