i have a Base class and Derived class.
they have a virtual function- virtual void action()
how can i pass it to *pthread_create()* function?
example(with errors):
class Base{
protected:
pthread_t tid;
public:
virtual void* action() = 0;
};
class Derived : public Base{
void* action();
Derived(){
pthread_create(&tid, NULL, &action, NULL);
}
};
maybe it should be static?
i tried lot of combinations but cant find solution..
I ran into this problem a couple months back working on my senior design project. It requires some knowledge of underlying C++ mechanics.
The underlying issue is that pointers to functions are different from pointers to member functions. This is because member functions have an implicit first parameter,
this.From the
manpage:The thread entrance point is a
void* (*)(void*). Your function,Base::actionhas the typevoid* (Base::*)(). TheBase::part of that ugly type declaration denotes the type ofthis. The type discrepancy is why the compiler won’t accept your code.There’s two things we need to fix to make this work. We can’t use a member function, because pointers to member functions don’t bind
thisto an instance. We also need a single parameter of typevoid*. Thankfully, these two fixes go hand in hand because the solution is to explicitly passthisourselves.Edit: Woops, if
tidisprotectedorprivate, thendo_actionneeds to be afriend.