1

I'm writing a class with pthreads in it, with it's header, and .cpp definition files.

In the .h i have:

class test
{
    public:
        int a;
    ...
    private:
        typedef void (*myfunc)(void *p);
        static myfunc pthreadRun;
}

In the .cpp i have:

...
typedef void (*myfunc)(void *p);
myfunc test::pthreadRun
{
    this->a = 10;
    pthread_exit(NULL);
}
...

I get an error: void (* test::pthreadRun)(void*) is not a static member of class test, and a bunch of other errors too, but this is the first one.

I'm confused as it is declared static :/

pthreadRun is the thread run function for pthread_create()

What am I missing?

Barney
  • 2,355
  • 3
  • 22
  • 37
Matekk
  • 683
  • 2
  • 8
  • 21

1 Answers1

1

It's hard to guess exactly what you are trying to do, but to start with I think I would rewrite your code like this:

class test
{
    public:
        int a;
    ...
    private:
        static void pthreadRun(void *p);
}

and

void test::pthreadRun(void *p)
{
    // this->a = 10; This line is now a big problem for you.
    pthread_exit(NULL);
}

So this is the kind of structure that you are looking for although you cannot access member elements (such as this->a) from this context because it is a static function.

Generally the way one handles this is by initiating the thread with the this pointer so that in the function you can:

void test::pthreadRun(void *p)
{
     test thistest=(test)p;
     thistest->a=10;  //what you wanted
     thistest->pthreadRun_memberfunction(); //a wrapped function that can be a member function
    pthread_exit(NULL);
}

You should be able to make all these functions private/protected (assuming you start the thread from within this class and I think it is probably preferable to do so.

Elemental
  • 7,365
  • 2
  • 28
  • 33