ambuj
ambuj

Reputation: 121

Error while calling function from pthread_create()

I have declared a function in the Class definition inside a header file:

class A
{
   public:
   ...
   void* func(void *);
   ...
}

In a .C file, I've a pointer to the class A's object as ptr.

Now, when i create a pthread:

iret1 = pthread_create(&thread1, NULL, ptr->func, NULL);

It throws an error as: error: a pointer to a bound function may only be used to call the function.

But when I declare the function func as static, this error doesn't come.

I just want to know a workaround for this as I can't change the function to static since I can't call other non-static members from it.

Upvotes: 0

Views: 459

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

You can't use non-static member functions as thread functions, or as functions to any non-C++ function expecting a function pointer. The reason is that all non-static member function has a hidden first argument that becomes the this pointer.

In this case it can be solved with a static proxy-function:

class A
{
public:
    void* func();

    static void* wrapper(void* object)
        { return reinterpret_cast<A*>(object)->func(); }
};

...

A* ptr = new A;
iret1 = pthread_create(&thread1, NULL, &A::wrapper, ptr);

This will create the thread with A::wrapper as the thread function, and pass the instance pointer as argument. The A::wrapper function then uses this argument as a pointer to the instance, and calls the real function.


However, if you have a C++11 capable compiler and standard library, there are much better support for threads:

A myA;
std::thread myThread(&A::func, &myA);

The above object creation creates a thread that will call A::func and pass the hidden first argument to the function as it needs.

Upvotes: 1

Related Questions