C++ OpenMP 程序
我试图使用以下代码在 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;
}
我已经多次运行该程序。由于并行性,我期望交错输出。
但是,每次运行该程序时,输出都是:
Hello World
Hello World
Hello World
Hello World
我在做什么吗有事吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是如何编译该程序的? OpenMP 是否已激活?
除此之外,如果你想获得交错字符,一个更简单的 Hello World 看起来像这样:
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:
代码是正确的,但是很难从这样的小程序中获得交错输出。尝试在输出语句之间放置一些对
sleep
或类似的调用,并进行一些刷新。(您是否使用
-openmp
、-fopenmp
或您的编译器想要听到的任何内容进行编译和链接?)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?)