1、通过CWinThread::CreateThread()创建线程
#include <afxwin.h>
#include <iostream>
UINT m_TimerId;
class ThreadClass : public CWinThread
{
public:
ThreadClass() { };
virtual BOOL InitInstance()
{
m_TimerId = ::SetTimer(NULL, 0, 1000, ThreadClass::TimerProc);
return TRUE;
}
virtual int ExitInstance()
{
::KillTimer(NULL, m_TimerId) ;
return CWinThread::ExitInstance();
}
virtual int Run()
{
return CWinThread::Run();
}
static VOID CALLBACK ThreadClass::TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
cout << "定时器执行了!" << GetCurrentTime() << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ThreadClass* ptest = new ThreadClass;
ptest->CreateThread();
while (true) {};
return 0;
}
ptest->CreateThread()后首先线程类的InitInstance()函数,如果返回TRUE,继续调用线程的Run()函数,该函数的作用是运行一个标准的消息循环,并且当收到WM_QUIT消息后中断,在消息循环过程中,Run()函数检测到线程空闲时(没有消息),也将调用OnIdle()函数,最后Run()函数返回,MFC调用ExitInstance()函数清理资源。
2、通过Windows API 函数CreateThread()创建线程
#include "stdafx.h"
UINT m_TimerId;
DWORD WINAPI ThreadProc(LPVOID lpParameter);
VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
{
cout << "定时器执行了!" << GetCurrentTime() << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE m_hWndThread;
m_hWndThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
CloseHandle(m_hWndThread);
while (true) {};
return 0;
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
m_TimerId = ::SetTimer(NULL, 0, 1000, TimerProc);
MSG msg;
while (true)
{
if (PeekMessage(&msg, 0, WM_TIMER, WM_TIMER, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}