Search code examples
c++openmpgoto

C++ goto inside an OMP parallel loop


Is it correct to use goto inside omp parallel loop to move only inside it's body? (I know that goto is not the best style of writing code)

int read_arr[N]; // example array
int write_arr[N];  // example array
std::recursive_mutex m;

#pragma omp parallel for
for (int i = 0; i < N; ++i) {
    LBL1:
    for (size_t k = 0; k < 10; k++)
    {
        bool flag = do_smth(k+i + read_arr[k]);
        if (flag)
        {
            m.lock();
            write_arr[i] = i + k;
            m.unlock();
        }
        else
        {
            m.lock();
            write_arr[i] = -1;
            m.unlock();
            goto LBL1;
        }
    }
}

Solution

  • As @VictorEijkhout says, you can use any control flow you like (including goto, or even setjmp/longjmp, or throw/catch) to transfer control inside a single thread without that violating OpenMP rules.

    As others point out, there's absolutely no need for a goto in this example (break is the normal way to leave a loop).

    Not what you asked, but there's also no need to use any locking here. Only a single thread will have any given value of i, so there are no race conditions that you need to avoid.