Threads and class member functions

Started by
3 comments, last by Martee 22 years, 10 months ago
How can I use a class member function as the starting point for a new thread via CreateThread()? Perhaps some code would explain it better...
    
class Foo
{
public:
	Foo();
	unsigned long WINAPI doStuff(void*);
};

Foo::Foo()
{
	unsigned long threadId;
	CreateThread(NULL, NULL, doStuff, NULL, NULL, &threadId);
}

unsigned long WINAPI Foo::doStuff(void* bar)
{
	while(true)
		do_more_stuff();
}
  
Doing it like this doesn't work, of course. I get the error, "cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'". Is there any way to do this? (Yeah, I know, it's probably something incredibly stupid and obvious ... ) ~~~~~~~~~~ Martee http://www.csc.uvic.ca/~mdill Edited by - Martee on June 20, 2001 9:07:10 PM
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
Advertisement
I believe you cannot have a thread run a class method because it wouldn''t be able to pass the implicit this . You may be able to pull it off if the class method is static, but I havn''t been able to.


Mike
"Unintentional death of one civilian by the US is a tragedy; intentional slaughter of a million by Saddam - a statistic." - Unknown
Ah well. There goes my brilliant idea . I guess it''s time for a bit of redesign.
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
Yes, the callback has to be static, but you can go right into a member function:
      class Foo{private:  unsigned long workerThread () {    while (true)      do_stuff ();    return val;  }  static unsigned long threadStub (void *arg) {    return ((Foo*) arg)->workerThread ();  }  public:  Foo () {    CreateThread (NULL, NULL, threadStub, this, NULL, &threadId);  }};      


Edited to fix bug--thanks, jaxson

Edited by - Stoffel on June 21, 2001 2:47:44 AM
I was going to tell you how, but Stoffel beat me to it There is one small mistake. It should be:

CreateThread (NULL, NULL, threadStub, this, NULL, &threadId);

This topic is closed to new replies.

Advertisement