- 使用Windows API 封装一个Thread类库
该
Thread
类被继承后,实现派生类自己的run
函数即可注:
_beginthreadex
的第三个参数传入的是函数指针,静态函数指针或非静态函数指针均可;如果是传入的是类的函数,则该函数应为静态函数。
Thread.h
#ifndef __THREAD__
#define __THREAD__
#include <Windows.h>
#include <tchar.h>
#include <process.h>
class Thread
{
protected:
HANDLE hThread;
unsigned uiThreadId;
static unsigned __stdcall _run(void * pThis)
{
Thread * pthX = (Thread *)pThis;
pthX->run();
return 1;
}
virtual void run() = 0;
public:
void start(DWORD nTimeOutMs=-1)
{
this->hThread = (HANDLE) _beginthreadex(
NULL,
0,
Thread::_run,
this,
CREATE_SUSPENDED,
&uiThreadId
);
ResumeThread(hThread);
if (nTimeOutMs != -1 && nTimeOutMs >= 0)
WaitForSingleObject(hThread, nTimeOutMs);
}
~Thread()
{
CloseHandle(hThread);
}
};
#endif