Rohan Shankar
Rohan Shankar

Reputation: 71

Pthread and function pointers

I am a little confused on how pthread works - specifically, I am pretty sure that pthread takes in a pointer to a function that takes a void pointer as an argument (correct me if I am wrong), and I have declared my function in that way, but I am still getting an error. Here is the code I am struggling with:

void eva::OSDAccessibility::_resumeWrapper(void* x)
{
    logdbg("Starting Connection.");
    _listener->resume();
    logdbg("Connected.");
    pthread_exit(NULL);
}

void eva::OSDAccessibility::resumeConnection()
{    
    long t;
    _listener->setDelegate(_TD);
    pthread_t threads[1];
    pthread_create(&threads[0], NULL, &eva::OSDAccessibility::_resumeWrapper, (void *)t);

}

The error I'm getting is:

No matching function for call to pthread_create.

You don't necessarily have to tell me how to fix the code (although that would be appreciated of course), I'm more interested in why this error is coming up and if my understanding of pthread is correct. Thanks! :)

Upvotes: 2

Views: 782

Answers (1)

Mathieu
Mathieu

Reputation: 9629

  1. Your function signature must be void * function (void*)

  2. If called from c++ code, the method must be static:

    class myClass
    {
        public:
        static void * function(void *);
    }
    

A solution to use methods that are not static is the following:

class myClass
{ 
    // the interesting function that is not an acceptable parameter of pthread_create
    void * function();

    public:
    // the thread entry point
    static void * functionEntryPoint(void *p)
    {
        ((myClass*)p)->function();
    }
}

And to launch the thread:

myClass *p = ...;
pthread_create(&tid, NULL, myClass::functionEntryPoint, p);

Upvotes: 2

Related Questions