/*shows how to start a thread based on a
class memeber function using a static member function.*/
#define WIN32_LEAN_AND_MEAN
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<process.h>
typedef unsigned(WINAPI *PBEGINTHREADEX_THREADFUNC)(LPVOID lpThreadParameter);
typedef unsigned *PBEGINTHREADEX_THREADID;
/*this threadobject is created by a
thread that wants to start another thread.
All public member functions except ThreadFunc()
are called by that original thread.The virtual function
ThreadMemberFunc()is the start og the new thread.
*/
class ThreadObject
{
public:
ThreadObject();
void StartThread();
void WaitForExit();
static DWORD WINAPI ThreadFunc(LPVOID param);
protected:
virtual DWORD ThreadMemberFunc();
HANDLE m_hThread;
DWORD m_ThreadId;
};
ThreadObject::ThreadObject()
{
m_hThread = NULL;
m_ThreadId = 0;
}
void ThreadObject::StartThread()
{
m_hThread = (HANDLE)_beginthreadex(NULL, 0,
(PBEGINTHREADEX_THREADFUNC)ThreadObject::ThreadFunc,
(LPVOID) this, 0, (PBEGINTHREADEX_THREADID)&m_ThreadId);
if (m_hThread)
printf("Thread lauched\n");
}
void ThreadObject::WaitForExit()
{
WaitForSingleObject(m_hThread, INFINITE);
CloseHandle(m_hThread);
}
//static member functions have no "this" pointer;
DWORD WINAPI ThreadObject::ThreadFunc(LPVOID param)
{
//Use the param as the address of the object
ThreadObject *pto = (ThreadObject*)param;
return pto->ThreadMemberFunc();
}
DWORD ThreadObject::ThreadMemberFunc()
{
//do something useful...
return 0;
}
void main()
{
ThreadObject obj;
obj.StartThread();
obj.WaitForExit();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。