Arnd Schroeter wrote:
Hello!
I am a c++ programmer under the os linux. I am using pthreads and i am
wondering why i can only use satic methods of a class to create a
thread of it. How can i change this, because it limits my programmes
very strongly. thanks in advance..Arnd Schröter
Threads are off-topic here, but I think your question is actually not
about threads, but about using callbacks in C with a C++ function.
Non-static member functions cannot be used. They need to be called for
an object, and how would the pthreads library know which object to call
the member function for? Further, the pthreads library is C, and so it
doesn't even know about objects and member functions.
Regarding static member functions: Actually, those probably work on many
platforms, but this is not guarranteed. You need to make your callback
function a non-member function that is declared extern "C" or be sure
that all platforms/compiler combinations you want to support have the
same calling conventions for C and C++.
There is still a way to call a member function, indirectly. pthreads,
like any other C library with a callback interface (at least those I
that know), provide an additional parameter of type void* that is
passed to the callback function. You can use that pointer to pass your
object. Something like this (untested and unfinished) should show you
the idea:
class Thread
{
public:
Thread();
//...
virtual void run() = 0;
//...
private:
pthread_t id_;
};
//pthread_create needs void* both for parameter and return type
extern "C"
void* thread_routine(void* obj)
{
static_cast<Thread*>(obj)->run();
return obj; //or whatever else you might need
}
Thread::Thread()
{
pthread_create(&_id, 0, thread_routine, this);
}