/*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 ()
is 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 has 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 ();
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A thread is started by a member function