Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ OpenMP program

Tags:

c++

openmp

I am trying to get a parallel effect in C++ program using the following code:

#include<iostream>
using namespace std;

int main()
{

#pragma omp parallel sections
    {
#pragma omp section
        {
        cout<<"Hello";  
        cout<<" ";  
        cout<<"World";  
        cout<<endl;

        }
#pragma omp section
        {
        cout<<"H";
        cout<<"ello";
        cout<<" W";
        cout<<"orld";
        cout<<endl;
        }
#pragma omp section
        cout<<"Hello"<<" "<<"World"<<endl;
#pragma omp section
{       cout<<"Hello ";
        cout<<"World"<<endl;
}
    }
    return 0;
}

I had run this program many times.. I was expecting interleaved output due to parallelism..

However, every time I run this program the output is:

Hello World
Hello World
Hello World
Hello World

Am I doing something wrong?

Thanks

like image 334
Betamoo Avatar asked Jan 07 '11 16:01

Betamoo


2 Answers

How have you compiled the program? Is OpenMP activated?

Apart from that, a much simpler Hello World looks like this, if you want to get interleaving characters:

int main() {
    char const* str = "Hello world";
    unsigned const len = std::strlen(str);
    #pragma omp parallel for num_threads(4)
    for (unsigned thread = 0; thread < 4; ++thread)
        for (unsigned i = 0; i < len; ++i)
            std::cout << str[i] << std::endl;
}
like image 104
Konrad Rudolph Avatar answered Sep 20 '22 20:09

Konrad Rudolph


The code is correct, but interleaved output can be hard to get from such small programs. Try putting some calls to sleep or similar between output statements and do some flushing.

(Did you compile and link with -openmp, -fopenmp, or whatever your compiler want to hear?)

like image 45
Fred Foo Avatar answered Sep 21 '22 20:09

Fred Foo