Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

Nothing really exceptional is happening here

$
0
0

I took this example from B.Stroustrup new book "TCPL", pages 115 and 116.

#include <iostream>
#include <thread>

void f() { std::cout << "Hello "; }
struct F {
    void operator()() { std::cout << "Parallel World!\n"; }
};

void user()
{
    std::thread t1 {f}; // f() executes in separate thread
    std::thread t2 {F()}; // F()() executes in separate thread
    t1.join(); // wait for t1
    t2.join(); // wait for t2
}

int main()
{
    user();
}

In one of the paragraphs on page 115 the author writes:

This is an example of a bad error: Here, f and F() each use the object cout without any form of synchronization. The resulting output would be unpredictable and could vary between different executions of the program because the order of execution of the individual operations in the two tasks is not defined. The program may produce ‘‘odd’’ output, such as

PaHerallllel o World!

But after executing this same code several times I always get the correct output. Please, don't bash me. I've just started studying threads.



Viewing all articles
Browse latest Browse all 15302

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>