Code:
#include <windows.h>
#include <iostream>
using namespace std;
class FooBar
{
HANDLE m_hthread;
DWORD m_threadid;
// static method for thread entry point
static DWORD WINAPI ThreadProc(LPVOID lpv)
{
return reinterpret_cast<FooBar*>(lpv)->ThreadMethod();
}//ThreadProc
// member function called by static thread entry point
DWORD ThreadMethod()
{
for (int n = 0; n < 5; n++)
{
cout << "Look at me! I'm a thread!!" << endl << flush;
::Sleep(1000);
}//for
return 0;
}//ThreadMethod
public:
FooBar() : m_hthread(NULL), m_threadid(0) {}
~FooBar()
{
// stop thread here if need be
if (m_hthread != NULL)
{
::CloseHandle(m_hthread);
}//if
}//destructor
// start the thread running
bool StartThread()
{
m_hthread = ::CreateThread(NULL, 0, FooBar::ThreadProc,
reinterpret_cast<void*>(this),
0, &m_threadid);
return m_hthread != NULL;
}//StartThread
// wait for the thread to exit
bool Join()
{
if (m_hthread == NULL)
return false;
return ::WaitForSingleObject(m_hthread, INFINITE) == WAIT_OBJECT_0;
}//Join
};//FooBar
int main()
{
FooBar fb;
fb.StartThread();
// wait for the thread to exit
fb.Join();
return 0;
}//main
gg