using member functions in pthreads (Linux)
I'm trying to use the following:
pthread_create(&searchThread[i], &threadAttribs[i], DoStuff, &ParallelParams[i]);
If DoStuff is static it compiles but then I do not have access to any of the methods or variables that are part of the class that DoStuff is in. But if I keep DoStuff as a non-static method so that I can access everything else in the class I get the following compiler error:
error: argument of type 'void* (MyClass::)(void*)' does not match 'void* ()(void)'
where the error seems to be referring to the DoStuff argument and the fact that it's a member function.
Is there any hope of being able to pass in a non-static method allowing me access to everything in MyClass in my DoStuff method?
Thanks!
pthreads expects a void* startfunc(void*)
signature and a non-static member function has the hidden this
pointer so you have to get around that. An easy way is to create a static helper function in the class. Use that as the start function and pass the object you want to access in the 4th (data) parameter. Something like so:
class Foo
{
public:
void *runThis(void)
{
std::cout << "Thread accessing this member function" << std::endl;
return 0;
}
static void *runHelper(void *classRef)
{
return ((Foo *)classRef)->runThis();
}
};
int main(int argc, char *argv[])
{
Foo foo;
pthread_t t;
pthread_create(&t, NULL, &Foo::runHelper, &foo);
pthread_join(t, NULL);
}
There are some fancier template methods that amount to something like the above but are more generic.
链接地址: http://www.djcxy.com/p/96368.html上一篇: 从静态方法访问类成员