I am starting to learn threads in the C++11 standard and I was trying out a very basic program which creates 10 threads, joins them and then exits. In the thread function, I tried to print out the index of the for loop that I'm creating the threads in, like this:
std::vector<std::thread> threads;
for(int i = 0; i < 10; i++)
{
threads.push_back(std::thread([i](){ printf("Thread #%d\n", i); }));
}
And this produces an output expected from a concurrent program, the threads execute out of order:
Thread #0
Thread #2
Thread #1
Thread #3
Thread #4
Thread #5
Thread #6
Thread #7
Thread #8
Thread #9
But when I try to do the same thing using std::cout
and std::endl
, I get this:
Thread #0
Thread #Thread #2
Thread #3
Thread #9
1
Thread #8
Thread #4
Thread #5
Thread #7
Thread #6
Why is this happening with std::cout
but not with printf
?