Total editing:
In order to prevent the simultaneous use of multiple streams cout, it will lead to a succession of characters, proceed as follows:
1) to declare to the ad f ():
static std::mutex m;
2), then protect "cout" line between:
m.lock(); std::cout<<"Hello world from : "<<i<<std::endl; m.unlock(); :" << i << std :: endl; m.lock(); std::cout<<"Hello world from : "<<i<<std::endl; m.unlock();
Apparently, binding to -lpthread library is mandatory for some unclear reasons. At least on my machine, but do not bind to -lpthread, resulting in core dump. Adding -lpthread leads to the correct functionality of the program.
Possibility of altering characters, if the lock is not used when accessing from different streams cout expressed here:
fooobar.com/questions/66118 / ...
more precisely: "[Note: users must synchronize the simultaneous use of these objects, and streams of multiple threads, if they want to avoid the alternate characters - end note.]"
OTOH, a race condition is guaranteed, at least in the standard C ++ 11 (be careful, the implementation of this standard gcc / g ++ is still at the experimental stage).
Note that the Microsoft implementation (see. Http://msdn.microsoft.com/en-us/library/c9ceah3b.aspx credit for @SChepurin) more strict than the standard (apparently, it ensures the alternation character is excluded) but this may not be the case for gcc / g ++ implementation.
This is the command line that I use to compile (as updated and original versions of the code, it works well on my PC):
g++ threadtest.cpp -std=gnu++11 -lpthread -O3
OTOH, without -lpthread, it compiles, but I have a core dump (gcc 4.7.2 on Linux 64).
I understand that you are using two different versions of gcc / g ++ compiler on the same computer. Just make sure you use them correctly (without mixing different versions of the library).