今天写了个测试程序,想要看看线程的创建,退出内核模式时间,和用户模式时间
#include <windows.h>
#include <iostream>
#include <process.h>
using namespace std;
unsigned int WINAPI WorkThread(void* param);
typedef HANDLE (WINAPI * OPENTHREADFUN)(DWORD dwDesiredAccess,BOOL bInheritHandle,DWORD dwThreadId);
int main()
{
FILETIME CreatTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
HANDLE hThread;
GetThreadTimes(GetCurrentThread(),&CreatTime,&ExitTime,&KernelTime,&UserTime);
cout<<"CreatTime:"<<CreatTime.dwHighDateTime<<","<<CreatTime.dwLowDateTime<<endl;
cout<<"ExitTime:"<<ExitTime.dwHighDateTime<<","<<ExitTime.dwLowDateTime<<endl;
cout<<"KernelTime:"<<KernelTime.dwHighDateTime<<","<<KernelTime.dwLowDateTime<<endl;
cout<<"UserTime:"<<UserTime.dwHighDateTime<<","<<UserTime.dwLowDateTime<<endl;
hThread=GetCurrentThread();
//DuplicateHandle(GetCurrentProcess(),GetCurrentThread(),GetCurrentProcess(),&hThread,0,false,DUPLICATE_SAME_ACCESS);
HANDLE hThreadNew=(HANDLE) _beginthreadex(NULL,0,WorkThread,(void*)hThread,0,NULL);
WaitForSingleObject(hThreadNew,INFINITE);
CloseHandle(hThreadNew);
CloseHandle(hThread);
system("pause");
return 0;
}
unsigned int WINAPI WorkThread(void* param)
{
HANDLE hThread=(HANDLE)param;
if(NULL==hThread)
{
return 1;
}
FILETIME CreatTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
GetThreadTimes(hThread,&CreatTime,&ExitTime,&KernelTime,&UserTime);
cout<<"CreatTime:"<<CreatTime.dwHighDateTime<<","<<CreatTime.dwLowDateTime<<endl;
cout<<"ExitTime:"<<ExitTime.dwHighDateTime<<","<<ExitTime.dwLowDateTime<<endl;
cout<<"KernelTime:"<<KernelTime.dwHighDateTime<<","<<KernelTime.dwLowDateTime<<endl;
cout<<"UserTime:"<<UserTime.dwHighDateTime<<","<<UserTime.dwLowDateTime<<endl;
return 0;
}
其实以上代码的想法很简单,就是通过GetThreadTime来查看主线程的创建,退出,内核,用户时间
另外我也想在子线程中调用GetThreadTime来查看主线程的创建,退出,内核,用户时间
测试结果:
但是我发现在主线程中的调用结果和子线程中的调用结果不一样,为什么呢?我明明把主线程的句柄通过param参数传递给子线程了
假设在子线程中的调用结果不是主线程的时间难道是子线程的时间
GetCurrentThread()是个伪句柄,我把这个值传递给子线程,难道,在子线程中调用GetCurrentThread返回的值和主线程中调GetCurrentThread返回的值是一样的,这样就解释了为什么时间会不一样,因为传递这个值相当于传递GetThreadTime的第一个参数传递GetCurrentThread函数的返回值
我做了个测试
在原有代码的子线程函数上加上了显示GetCurrentThread返回的句柄值
unsigned int WINAPI WorkThread(void* param)
{
HANDLE hThread=(HANDLE)param;
//cout<<"ThreadHandle:"<<hThread<<endl;
FILETIME CreatTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
cout<<"主线程:"<<hThread<<endl;
cout<<"子线程:"<<GetCurrentThread()<<endl;
GetThreadTimes(hThread,&CreatTime,&ExitTime,&KernelTime,&UserTime);
cout<<"CreatTime:"<<CreatTime.dwHighDateTime<<","<<CreatTime.dwLowDateTime<<endl;
cout<<"ExitTime:"<<ExitTime.dwHighDateTime<<","<<ExitTime.dwLowDateTime<<endl;
cout<<"KernelTime:"<<KernelTime.dwHighDateTime<<","<<KernelTime.dwLowDateTime<<endl;
cout<<"UserTime:"<<UserTime.dwHighDateTime<<","<<UserTime.dwLowDateTime<<endl;
return 0;
}
不出我所料,果然是一样的,附上测试结果
敬请下回分解