• Advertisement

Archived

This topic is now archived and is closed to further replies.

Threads and class member functions

This topic is 6152 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites

  • Advertisement