1.线程何时开始:创建时候开始
2.何时结束:线程函数结束时候结束;到TerminateThread或者ExitThread时候退出,还有一种情况就是,在主线程或者线程所在进行结束的时候也结束(这里没有测试代码,但是可以通过在控制台main函数中创建一个线程,在线程处理函数中使用while(1),这样线程函数不会结束,但是再关掉这个进程的时候线程也不工作了来验证)。
测试代码如下:
#include <iostream>
#include <process.h> //这个头文件中有CreateThread(),ExitThread(),CloseHandle()函数
#include <Windows.h>
#include <stdio.h>
using namespace std;
HANDLE handle;
DWORD dw;
DWORD WINAPI MyThread(void *p)
{
cout << "My Thread ID:" << GetCurrentThreadId() << endl;
GetExitCodeThread(handle,&dw);
if (dw == STILL_ACTIVE)
cout << "Thread Is Still Active!" << endl;
/*while (STILL_ACTIVE == dw)
{
}*/
//ExitThread(3);
cout << "can go here now" << endl;
Sleep(10000);
return 0;
}
int main()
{
handle = CreateThread(NULL,0,MyThread,NULL,0,&dw);
Sleep(5000);//程序执行到这里延迟100毫秒(millionsecond)
GetExitCodeThread(handle,&dw);
if (dw != STILL_ACTIVE)
{
cout << "Exit Code is:" << dw << endl;
}
else
{
cout << "Thread Is Still Active!" << endl;
}
Sleep(6000);
GetExitCodeThread(handle,&dw);
if (dw != STILL_ACTIVE)
{
cout << "Exit Code is:" << dw << endl;
}
else
{
cout << "Thread Is Still Active!" << endl;
}
CloseHandle(handle);
return 0;
}