0

I have put 3 tasks in parallel: print min, max, and average of two numbers. The first task prints min value twice, and I expect it's output to be contiguous.

int wmain()
{

__int64 elapsed;

    elapsed = time_call([&] 
    {
        double a = 1.0;
        double b = 5.0;
        parallel_invoke(
            [&]{for( size_t i = 0; i < 2; ++i )
                {
                    PrintMinValue(a, b);
                }},
            [&]{PrintMaxValue(a, b);},
            [&]{PrintAvgValue(a, b);});

    }); 

    wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;
}

I ran this program several times. All outputs such as 5, 3, 1, 1 or 3, 1, 1, 5 are understandable. However, some outputs such as 1, 5, 3, 1 are not obvious. It means that the first task that must print "1" (min value) twice in a contiguous block is split. Why?

2 Answers2

0

every call to wcout or cout can be split at the '<<' operator, if you want to print a whole line without breaks use printf style output.

Rick
  • 3,145
  • 15
  • 17
0

The code is executed in parallel. Why do you expect blocks to be contiguous? The whole point about parallel programming is that you give this guarantee up – otherwise it wouldn’t be parallel but sequential.

If you want to preserve the sequence of execution then you need to wrap your contiguous block in a critical section.

Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
  • @EugeneZak that changes absolutely nothing. The **only** thing that your code ensures is that the instructions in the *first* block are not executed at the same time, and in sequence. But their relation to the other instructions is not defined. That is the whole point of parallel execution. – Konrad Rudolph Mar 18 '13 at 17:14
  • Thank you, it makes sense. – Eugene Zak Mar 18 '13 at 17:38