Results 1 to 4 of 4
I am trying to use a C++ class method as a thread. For the example below the gcc compiler returns " error: argument of type `void*(foo:: )(void*)' does not match ...
- 07-02-2009 #1Just Joined!
- Join Date
- Nov 2006
- Posts
- 3
pthread using C++ method?
I am trying to use a C++ class method as a thread. For the example below the gcc compiler returns " error: argument of type `void*(foo:: )(void*)' does not match `void*(*)(void*)'". Program copiles and runs fine if the footest thread line is commented out.
Is there a way I can cast this correctly?
Example:
Thanks.Code:#include <stdio.h> #include <stdlib.h> #include <pthread.h> class foo { public: void *bar(void * threadid) { printf("foo.bar, threadid =%ld\n", (long)threadid); pthread_exit(NULL); } }; void *PrintHello(void *threadid) { printf("PrintHello, threadid =%ld\n", (long)threadid); pthread_exit(NULL); } int main (int argc, char *argv[]) { foo footest; pthread_t thread; int rc; long t = 1; printf("In main: creating thread %ld\n", t); rc = pthread_create(&thread, NULL, footest.bar, (void *)t++); rc = pthread_create(&thread, NULL, PrintHello, (void *)t++); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } footest.bar((void*) t); pthread_exit(NULL); }
- 07-02-2009 #2
I don't think you can do this using C++ since what your asking breaks down encapsulation...Gerard4143
Note you could do a
Objdump -D filename>testfile
and extract the address of the class function that way but then you may have to maintain the stack manually when you call the class function...
If memory serves, I tried something like this a while ago...I never got it working...G4143Make mine Arch Linux
- 07-04-2009 #3Just Joined!
- Join Date
- Aug 2007
- Posts
- 7
Hey Devanski,
You can definitely use a class function to start a thread, the catch is it needs to be static.
The basic idea is to setup an abstract base class called CThread, with a static method run, and a virtual method execute.
Derive a child class from CThread, and implement any desired functionality in execute. In the base class, implement run to call execute. When you call pthread_create, you'll pass in the static function run, and as the user data to the thread, pass the 'this' pointer for your derived class. Using the this pointer you can call execute and you'll be up and running.
From there you can add tons of other methods to your thread class, but that gives you the basics for starting up a thread.
If you google around you'll find lots of example implementations of this.
- 07-06-2009 #4Just Joined!
- Join Date
- Nov 2006
- Posts
- 3
Thanks for the response. I will go that route.


Reply With Quote