ThreadProc as a method

Started by
2 comments, last by drekkar 20 years, 10 months ago
How can I get a ThreadProc to be a method of a class? =( Here''s what I got...

class CTheClass
{
public:
  CTheClass();
  ~CTheClass();
  DWORD WINAPI ThreadProc(LPVOID lpParameter);
private:
  DWORD m_pid;
};

CTheClass::CTheClass(){
  CreateThread(0, 0, ThreadProc, 0, 0, &m_pid);
}

CTheClass::~CTheClass(){

}

DWORD WINAPI CTheClass::ThreadProc(LPVOID lpParameter){
  return 0;
}
 
it''s being weird on me because the threads callback is a method, is there a way to make it work? Of course I could make the thread proc global and make all the members public, but I dont want to hear that =P Then again it could be possible that callbacks were not meant to be methods... I am not amazingly experienced with callbacks and such. Enlighten me please =)
Advertisement
make it static.

if access to the class members is needed, the "this" pointer can be set as the parm that gets passed into the callback and then that can be cast to a pointer to the class.
quote:Original post by Anonymous Poster
make it static.

if access to the class members is needed, the "this" pointer can be set as the parm that gets passed into the callback and then that can be cast to a pointer to the class.


Yeah, that''s the way to do it. Something like this, maybe:
class CTheClass{ public: CTheClass(); ~CTheClass(); static DWORD WINAPI sThreadProc(LPVOID param); //the ''s'' is for ''static'' DWORD ThreadProc();protected: DWORD m_pid;};CTheClass::CTheClass(){  CreateThread(0, 0, sThreadProc, this, 0, &m_pid);}CTheClass::~CTheClass(){}DWORD WINAPI CTheClass::sThreadProc(LPVOID lpParameter){  return ((CTheClass*)lpParameter)->ThreadProc();}DWORD CTheClass::ThreadProc(){ //whatever you want return 0;} 


Like that. You lose out on your ability to pass a parameter to the thread - you have to use a member variable instead that you set up beforehand - and you should probably check that lpParameter isn''t NULL in sThreadProc, though I don''t think that could ever happen.

Superpig
- saving pigs from untimely fates, and when he''s not doing that, runs The Binary Refinery.

Richard "Superpig" Fine - saving pigs from untimely fates - Microsoft DirectX MVP 2006/2007/2008/2009
"Shaders are not meant to do everything. Of course you can try to use it for everything, but it's like playing football using cabbage." - MickeyMouse

thanks a ton guys =)

This topic is closed to new replies.

Advertisement