Search code examples
c++openmpcancellation

Enable cancellation of openmp threads from inside program


According to the OpenMP specification, OMP_CANCELLATION must be set to true in order for statements like #pragma omp cancel to have any effect. I need the cancellation functionality to be enabled for my program to work properly (a GUI abort button that triggers the cancellation, if it matters).

I tried to set OMP_CANCELLATION from within the program with

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

as the first line of the program, but this statement does not have any effect. If I manually export OMP_CANCELLATION=true from a shell outside before running the program, the cancellation works properly.

Is it possible to enable cancellation from within the program without requiring this environment variable to be set externally?


Solution

  • Although it is not possible to enable cancellation once the program starts (as per Zulan's answer), I managed to find a workaround:

    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");
    }
    

    I set the variable in the program and then use an exec call to restart the process. The restarted process will have OMP_CANCELLATION properly set before it starts.