1. 基类
class CWorkerThread : public CObject
{
DECLARE_DYNAMIC(CWorkerThread)
public:
CWorkerThread()
{
m_pHost = NULL;
}
virtual ~CWorkerThread()
{
}
// Attributes
public:
// Operations
public:
void StartThread()
{
AfxBeginThread(GenericThreadFunc, this);
}
// Overrides
virtual UINT ThreadFunc()
{
//ASSERT(m_pHost);
return 0L;
}
LPVOID GetHost()
{
return m_pHost;
}
void SetHost(LPVOID pHost)
{
ASSERT(pHost);
m_pHost = pHost;
}
// Implementation
private:
static UINT GenericThreadFunc(LPVOID lp_)
{
CWorkerThread* m_pWrapper = (CWorkerThread*)lp_;
return m_pWrapper->ThreadFunc();
}
LPVOID m_pHost;
};
2. 具体类
class CMainFrame;
class CMyWorkerThread : public CWorkerThread
{
public:
CMyWorkerThread();
virtual ~CMyWorkerThread();
virtual UINT ThreadFunc();
};
UINT CMyWorkerThread::ThreadFunc()
{
ASSERT(((CMainFrame*)m_pHost)->IsKindOf(RUNTIME_CLASS(CMainFrame)));
for (int _i = 0; _i < 4000; _i++)
{
// if (WAIT_OBJECT_0 == WaitForSingleObject(m_pHost->m_hExitEvent, 0))
// return 1L;
TRACE("Hello, Thread/n" );
}
return 0L;
}
3. 使用
CMyWorkerThread m_MyThread;
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
//...
m_MyThread.SetHost(this);
m_MyThread.StartThread();
return 0;
}