简体   繁体   English

C ++ OpenMP程序

[英]C++ OpenMP program

I am trying to get a parallel effect in C++ program using the following code: 我试图使用以下代码在C ++程序中获得并行效果:

#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? OpenMP是否已激活?

Apart from that, a much simpler Hello World looks like this, if you want to get interleaving characters: 除此之外,如果你想要交错字符,一个更简单的Hello World看起来像这样:

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. 尝试在输出语句之间调用一些sleep或类似的调用并进行一些刷新。

(Did you compile and link with -openmp , -fopenmp , or whatever your compiler want to hear?) (您是否编译并链接了-openmp-fopenmp或编译器想要听到的内容?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM