Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process return in OpenMP parallel code?

My requirement is like this: every thread allocates memory itself, then processes it:

typedef struct
{
    ......
}A;

A *p[N];

#pragma omp parallel
{
    #pragma omp for
    for (int i = 0; i < N; i++) {
        p[i] = (A*)calloc(sizeof(*p[i]), N);
        if (NULL == p[i]) {
            return;
        }
        ......          
    }
}

But the compiler will complain:

error: invalid exit from OpenMP structured block
     return;

So except put the allocating memory code out of the #pragma omp parallel:

for (int i = 0; i < N; i++) {
    p[i] = (A*)calloc(sizeof(*p[i]), N);
    if (NULL == p[i]) {
        return;
    }       
}
#pragma omp parallel
{
    #pragma omp for
    ......
}

Is there any better method?

like image 740
Nan Xiao Avatar asked Sep 19 '26 00:09

Nan Xiao


2 Answers

You're looking for this, I think:

#pragma omp parallel
{
    #pragma omp for
    for (int i = 0; i < N; i++) {
        p[i] = (A*)calloc(sizeof(*p[i]), N);
        if (NULL == p[i]) {
            #pragma omp cancel for
        }
        ......          
    }
}

But you'll need to set the environment variable OMP_CANCELLATION to true for this to work.

You should try to avoid doing this, though, because cancellation is expensive.

like image 91
Richard Avatar answered Sep 21 '26 15:09

Richard


You could try this

omp_set_dynamic(0); //Explicitly turn off dynamic threads
bool cancel = false;    

#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
    p[i] = (A*)calloc(sizeof(*p[i]),N);
    if (NULL == p[i]) cancel = true;
}
if(cancel) return;
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
    ......   
}

This could allocate the memory local to each core/node. I turned off dynamic adjusting the number of threads and used schedule(static) to make sure the threads in the second for loop access the same memory allocated in the first for loop.

I don't know if this solution would be any better. According to this comment it could be worse. It could make a big difference if you have a multi-socket (NUMA) system or not.

like image 32
Z boson Avatar answered Sep 21 '26 13:09

Z boson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!