Let's say I have a class such as
class c {
// ...
void *print(void *){ cout << "Hello"; }
}
And then I have a vector of c
vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());
Now, I want to create a thread on c.print();
And the following is giving me the problem below: pthread_create(&t1, NULL, &c[0].print, NULL);
Error Ouput: cannot convert ‘void* (tree_item::)(void)’ to ‘void* ()(void)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’
You can't do it the way you've written it because C++ class member functions have a hidden
this
parameter passed in.pthread_create()
has no idea what value ofthis
to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has nothis
parameter), or a plain ordinary function to bootstrap the class:Too many times I've found ways to solve what you are asking for that, in my opinion are too complicated. For instance you have to define new class types, link library etc. So I decided to write a few lines of code that allow the end user to basically be able to "thread-ize" a "void ::method(void)" of whatever class. For sure this solution I implemented can be extended, improved etc, so, if you need more specific methods or features, add them and please be so kind to keep me in the loop.
Here are 3 files that show what I did.
// The class that incapsulates all the work to thread-ize a method (test.h):
// A usage example file "test.cc" that on linux I've compiled with The class that incapsulates all the work to thread-ize a method: g++ -o mytest.exe test.cc -I. -lpthread -lstdc++