I am trying out some examples from C++11 threads I see some surprising results. With the following code
#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello concurrent world " << std::endl;
}
void do_something() {
std::cout << "[background_task] --> [ do_something ]" << std::endl;
}
void do_something_else() {
std::cout << "[background_task] --> [ do_something_else ]" << std::endl;
}
class background_task {
public:
void operator()() const {
do_something();
do_something_else();
}
};
int main ( int argc, char **argv) {
std::thread t(hello);
background_task bt;
std::thread fn_obj_th(bt);
t.join();
fn_obj_th.join();
}
output is as follows
Hello concurrent world [background_task] --> [ do_something ]
[background_task] --> [ do_something_else ]
Press any key to continue . . .
If I replace
std::cout << "Hello concurrent world " << std::endl;
with
std::cout << "Hello concurrent world \n";
Result is
Hello concurrent world
[background_task] --> [ do_something ]
[background_task] --> [ do_something_else ]
Why in case with std::endl I am not getting expected output.
This:
is two separate outputs. While
std::coutis thread-safe, that doesn’t mean that two separate invocations of it is guaranteed to be atomic. A single output is atomic, but not two.If you want a particular expression to be guaranteed to be atomically output, then you need to add your own synchronization primitives on top of
std::cout.