开发者

C++ OpenMP program

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


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;
}


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?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜