0

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.

2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.