允许从程序内部取消 openmp 线程

Enable cancellation of openmp threads from inside program

根据 OpenMP 规范,OMP_CANCELLATION 必须设置为 true 才能使 #pragma omp cancel 等语句生效。我需要为我的程序启用取消功能才能正常工作(如果重要的话,触发取消的 GUI 中止按钮)。

我尝试在程序中设置 OMP_CANCELLATION

setenv("OMP_CANCELLATION", "true", 1);

作为程序的第一行,但是这条语句没有任何作用。如果我在 运行 程序之前从外部的 shell 手动 export OMP_CANCELLATION=true,取消工作正常。

是否可以在程序内部启用取消而不需要在外部设置此环境变量?

根据 standard (Chapter 4) 不可能:

Modifications to the environment variables after the program has started, even if modified by the program itself, are ignored by the OpenMP implementation. However, the settings of some of the ICVs can be modified during the execution of the OpenMP program by the use of the appropriate directive clauses or OpenMP API routines.

没有指定这种修改cancel-var值的方法(2.3.3)。

您可以通过编写包装器来解决该问题 program/script。

一些实现可以提供修改值的方法,而不管标准怎么说。但是依赖它是不可移植的。

虽然程序启动后无法启用取消(根据 Zulan 的回答),但我设法找到了解决方法:

char *hasCancel = getenv("OMP_CANCELLATION");
if (hasCancel == nullptr) {
    printf("Bootstrapping...");
    setenv("OMP_CANCELLATION", "true", 1);
    // Restart the program here
    int output = execvp(argv[0], argv);
    // Execution should not continue past here
    printf("Bootstrapping failed with code %d\n",output);
    exit(1);
} else {
    puts("Bootstrapping complete");
}

我在程序中设置变量,然后使用 exec 调用重新启动进程。重新启动的进程将在启动前正确设置 OMP_CANCELLATION