// threadfunctor.h // --------------- // C == Class type // R == Thread function Return type // A == Thread function Argument type template class CThreadFunctor { public: CThreadFunctor(C* sourceClass, R(C::*sourceMethod)(A)) :m_hThread(NULL), m_pClass(sourceClass), m_pfMethod(sourceMethod) { } ~CThreadFunctor() { // Wait and allow ThreadProc to finish, but kill it if it fails to terminate on its own if (WAIT_FAILED == ::WaitForSingleObject(m_hThread, INFINITE)) ::TerminateThread(m_hThread, 0); if (m_hThread) { ::CloseHandle(m_hThread); m_hThread = NULL; } } BOOL Init() { // Crate a thread for the processing m_hThread = ::CreateThread( NULL, 0, // Default stack size (LPTHREAD_START_ROUTINE) CThreadFunctor::ThreadProc, (LPVOID)this, 0, // Run thread immediately NULL); if (!m_hThread) return FALSE; return TRUE; } private: static DWORD WINAPI ThreadProc(LPVOID lpParam) { // Cast lpParam to the CThreadFunctor class and retrieve the data members C* pClass = ((CThreadFunctor*) lpParam)->m_pClass; R(C::*pfMethod)(A) = ((CThreadFunctor*) lpParam)->m_pfMethod; // Call the template method (pClass->*pfMethod)(); return 0; } private: HANDLE m_hThread; C* m_pClass; R(C::*m_pfMethod)(A); };