原来直觉以为线程Thread1中创建的线程Thread2是子线程,如果Thread1结束,Thread2也会结束,但是实际并不是,如下面的例子
DWORD WINAPI Thread2(LPVOID p);
DWORD WINAPI Thread1(LPVOID p)
{
HANDLE htest = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);
int i = 0;
while (i < 6)
{
cout << endl;
cout << "--------------Thread1-----------------" << endl;
Sleep(1000);
i++;
}
return 0;
}
DWORD WINAPI Thread2(LPVOID p)
{
while (true)
{
cout << endl;
cout << "--------------Thread2---------------" << endl;
Sleep(1000);
}
return 0;
}
int main()
{
CreateThread(NULL, 0, Thread1, NULL, 0, NULL);
输出如下,当Thread1结束后,Thread2还在一直的执行
--------------Thread1-----------------
--------------Thread2---------------
--------------Thread1-------------------------------Thread2---------------
--------------Thread1-----------------
--------------Thread2---------------
--------------Thread1-----------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread1-----------------
--------------Thread1-----------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------
--------------Thread2---------------