Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c++ - Parallel computing -- jumbled up output?

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:

Hello Wo

Hello World!

rld!

Hello World!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...