In the list below, I expect that when I call t.detach() immediately after the line when creating the stream, stream t will run in the background and printf("quit the main function now \n") is called and then main will come out.
#include <thread> #include <iostream> void hello3(int* i) { for (int j = 0; j < 100; j++) { *i = *i + 1; printf("From new thread %d \n", *i); fflush(stdout); } char c = getchar(); } int main() { int i; i = 0; std::thread t(hello3, &i); t.detach(); printf("quit the main function now \n"); fflush(stdout); return 0; }
However, from what it displays, this is not so. He is typing
From new thread 1 From new thread 2 .... From new thread 99 quit the main function now.
It appears that the main function is waiting for the thread to complete before it executes the printf("quit the main function now \n"); command printf("quit the main function now \n"); and will come out.
Could you explain why this is so? What am I missing here?
rudky source share