Function Pointer or Class Pointer ?
-
I have a class containing these methods/members :
class CWorkerThread
{
public:
CWorkerThread(const HANDLE* hJobSignal); // creates Win32-Thread
~CWorkerThread();private:
void run(); // member-function that does the actual work
static DWORD WINAPI StaticThreadFunction(LPVOID lpParameter); // entry-point for Win32-Threadsconst HANDLE\* m\_hJobSignal;
};
The constructor creates a Thread and passes it the StaticThreadFunction to execute. As parameter it can now pass either a pointer to run(), or a the this-pointer. Wich is better ? I really see no big difference, but i fear i might miss some important point here. Thanks !
-
I have a class containing these methods/members :
class CWorkerThread
{
public:
CWorkerThread(const HANDLE* hJobSignal); // creates Win32-Thread
~CWorkerThread();private:
void run(); // member-function that does the actual work
static DWORD WINAPI StaticThreadFunction(LPVOID lpParameter); // entry-point for Win32-Threadsconst HANDLE\* m\_hJobSignal;
};
The constructor creates a Thread and passes it the StaticThreadFunction to execute. As parameter it can now pass either a pointer to run(), or a the this-pointer. Wich is better ? I really see no big difference, but i fear i might miss some important point here. Thanks !
I favor passing a pointer to 'this'. Inside the static function, you cast the LPVOID to a 'this' pointer and then call the virtual function 'Run'. Therefore, if someone dervies from your thread class, the static function will always call the 'Run' of the derived class. I am not sure of the behavior if you pass in the Run pointer directly, from the base class, not sure you would get the Run of the dervied class to execute. My static thread runner functions typically have two lines in them:
DWORD WINAPI CWorkerThread::StaticThreadFunction(LPVOID lpParameter) { CWorkerThread* pRunner = (CWorkerThread*)lpParameter; return pRunner->Run(); }
It really is that simple!Any sufficiently gross incompetence is nearly indistinguishable from malice.