有时, 我们需要找出主线程. 下面示例代码给出windows下的一种方法:
原因很简单, 枚举当前进程的所有线程, 最早创建的那个必定是主线程.
-
m_threadId = 0;
-
FILETIME timeRunE = {0};
-
const DWORD idProcess = GetCurrentProcessId();
-
HANDLE hThreadSnap= ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, idProcess);//获取快照句柄
-
if(hThreadSnap == INVALID_HANDLE_VALUE)//如果获取失败返回
-
return;
-
THREADENTRY32 pe32 = { sizeof(pe32) };//快照结构并给予大小
-
if(::Thread32First(hThreadSnap, &pe32))
-
{
-
do
-
{
-
if ( pe32.th32OwnerProcessID == idProcess )//如果进程ID等于你想寻找的进程ID则返回主线程ID
-
{
-
HANDLE handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE,pe32.th32ThreadID);
-
-
FILETIME createtime,time2,time3,time4;
-
::GetThreadTimes(handle,&createtime,&time2,&time3,&time4);
-
SYSTEMTIME realtime;
-
::FileTimeToSystemTime(&createtime,&realtime);
-
if ( createtime.dwHighDateTime < timeRunE.dwHighDateTime
-
|| (timeRunE.dwHighDateTime == 0 && timeRunE.dwLowDateTime == 0) )
-
{
-
m_threadId = pe32.th32ThreadID ;
-
timeRunE = createtime;
-
} else
-
if ( createtime.dwHighDateTime == timeRunE.dwHighDateTime &&
-
createtime.dwLowDateTime < timeRunE.dwLowDateTime )
-
{
-
m_threadId = pe32.th32ThreadID ;
-
timeRunE = createtime;
-
}
-
}
-
}while(::Thread32Next(hThreadSnap, &pe32));
-
}//否则循环判断尾
-
::CloseHandle(hThreadSnap);
阅读(5190) | 评论(0) | 转发(0) |