Search code examples
copenmp

how to implement break function in openmp nested for loop


I know that you can't set breaks on OpenMP for loop but could you suggest an alternative which will break from nested for loop. How can I stop all threads to work after some result is found?

the code is attached here

#pragma omp parallel default(none) private( dict_len, success)
    {
        #pragma omp for collapse(5)
        for(int i=0; i<dict_len; i++) {
            for(int j=0; j<dict_len; j++) {
                for(int k=0; k<dict_len; k++) {
                    for(int l=0; l<dict_len; l++) {
                        for(int m=0; m<dict_len; m++) {
                            unsigned char* result = X;

                            if (success == 1) {

                                    #pragma omp critical
                                    {
                                        printf("%s\n", result);
                                    }
                                     #pragma omp cancel for
                            }
                            free(result);
                            printf("unsuccessful!\n");
                            #pragma omp cancellation point for  
                        }
                    }  
                }
            }
        }
    }

Solution

  • Your code works, but note the following points:

    • dict_len must be equal to all OpenMP workers. Prefer using firstprivate or shared instead private to this variable.
    • OpenMP does not activate for cancellation by default. You need to specify it setting the OMP_CANCELLATION environmental variable to true.