Passing shared variables as arguments to functions

The following code probably won’t have the desired behaviour, because we’re passing the shared variable ‘cnt’ on main by value. So the variable ‘cnt’ are local (private) to each processor and just are assigned the value 30. The right way is to pass the variable by reference.

#include <cstdio>
#include "omp.h"

void foo(int cnt){

    int id = omp_get_thread_num();

    while(1){

        int stop = false;

        #pragma omp critical
        {
            if (cnt > 0){
                (cnt)--;
                printf("[%d] iterando... %d\n", id, cnt);
            }
            else stop = true;
        }
        if (stop) break;
    }
}


int main (){

    int cnt = 30;

    #pragma omp parallel shared(cnt)
    {
        foo(cnt);        
    }

}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s