Windowsの下でCThreadパッケージクラスを実現
このクラス「CThread」からサブクラス「MyThread」を継承し、Run関数を書き換えると簡単です.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class CThread
{
public:
CThread();
virtual DWORD Run();
bool Start();
bool Join(DWORD nMillSec = 200);
private:
static DWORD WINAPI RunThread(LPVOID pParam);
HANDLE m_hThread;
LPVOID m_pParam;
DWORD m_nRet;
bool m_bStart;
};
CThread::CThread()
{
m_hThread = NULL;
m_pParam = NULL;
m_nRet = 0;
m_bStart = false;
}
DWORD CThread::Run()
{
return 0;
}
bool CThread::Start()
{
m_bStart = true;
m_hThread = CreateThread(NULL, 0, &RunThread, this, 0, NULL);
if (!m_hThread)
{
m_bStart = false;
return false;
}
return true;
}
bool CThread::Join(DWORD nMillSec)
{
while (m_bStart)
Sleep(nMillSec);
if (FALSE == GetExitCodeThread(m_hThread, &m_nRet))
return false;
else
{
CloseHandle(m_hThread);
return true;
}
}
DWORD WINAPI CThread::RunThread(LPVOID pParam)
{
CThread* pThis = (CThread*)pParam;
DWORD nRet = pThis->Run();
pThis->m_bStart = false;
return nRet;
}
class MyThread : public CThread
{
public:
DWORD Run();
};
DWORD MyThread::Run()
{
cout << "..." << endl;
return 0;
}
int main(int argc, char **argv)
{
MyThread my;
my.Start();
my.Join();
return 0;
}