并行计算――混乱的输出?

2021-12-30 00:00:00 c parallel-processing openmp c++

我正在尝试学习并行计算的基础知识,但我的计算机遇到了问题.看看我下面的代码.基本上,我想打印出Hello World!"这一行.对于我的计算机拥有的每个核心.我的电脑有四个核心,所以它应该打印出那行四次.如果我使用注释掉的 'cout' 行而不是 'printf' 行,输出将全部混乱.这是因为 ' ' 转义命令与Hello World!"是分开执行的,所以新行输出会随机出现.'printf' 行是这个问题的解决方案,因为该行是一次性执行的(不像 'cout' 行那样分成多个部分).但是,当我使用printf"时,我的输出仍然像使用cout"一样混乱.我不知道为什么会这样.我在另一台计算机上尝试了完全相同的代码,它运行良好.只有我的电脑继续用printf"来混淆输出.我已经给我的 CS 教授发了电子邮件,他不知道为什么它会在我的电脑上这样做.我知道我在计算机上正确设置了 OpenMP.有并行计算经验的人知道为什么这会在我的电脑上出现问题吗?

I'm trying to learn the basics of parallel computing, but I'm running into an issue on my computer. Take a look at my code below. Basically, I want to print out the line "Hello World!" for every core my computer has. My computer has four cores, so it should print out that line four times. If I were to use the commented-out 'cout' line instead of the 'printf' line, the output would be all jumbled up. This is because the ' ' escape command is executed separately from the "Hello World!", so the new line output would occur randomly. The 'printf' line is a solution to this problem, because the line is executed all at once (not split up into parts like the 'cout' line). However, when I use 'printf', my output is still all jumbled up as if I used 'cout'. I have no idea why it does this. I tried the exact same code on another computer, and it works perfectly. It's only my computer that continues to jumble up the output with 'printf'. I've emailed my CS professor about it, and he has no idea why it's doing this on my computer. I know I set up OpenMP on my computer correctly. Does anyone with parallel computing experience know why this is messing up on my computer?

#include <omp.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    #pragma omp parallel
    {
        printf("Hello World!
");
        //cout << "Hello World!
" << endl;
    }
    return 0;
}

为了说明我在说什么,这是我在计算机上运行上述代码时的输出:

To show what I'm talking about, here is the output from when I ran the above code on my computer:

你好沃

世界你好!

rld!

世界你好!

推荐答案

抱歉,你的教授弄错了.您需要利用互斥或其他一些障碍来保证不间断地使用共享资源(在本例中为 STDOUT 输出文件).

Sorry, your professor's mistaken. You need to leverage mutual exclusion or some other barriers in order to guarantee uninterrupted use of a shared resource (which in this case is the STDOUT output file).

混合输出是潜在的预期行为,无论 printfstd::cout::operator<<().由于设计不同,您看到的行为差异是每个执行持续时间的细微差异.无论哪种情况,您都应该期待这种行为.

Mixed output is potential expected behavior regardless of printf or std::cout::operator<<(). The differences in behavior you see are subtle differences in the execution duration of each, due to their differing design. You should expect this behavior in either case.

我只是不明白为什么它会适用于其他所有人.

I just don't understand why it would be working for everyone else.

不是.成为班级的英雄并解释它是如何工作的以及如何修复它.告诉他们 SO 发送他们的爱.:)

It's not. Be a hero to your class and explain how it works and how to fix it. Tell them SO sends their love. :)

相关文章