pthreads and a class function

Mar 18, 2009 at 2:10pm
i have just started learning pthreads in c++. i need to create a thread which will run a class function. but for some reason i'm getting an error.

here is what i'm doing:

1
2
3
4
5
6
MyClass.h file

class MyClass {
  public:
    void my_method(int d);
}


main.cpp file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <pthreads.h>
#include "MyClass.h"
#define THREAD_COUNT 3

int main (int argc, char** argv) {
  pthread_t thread[THREAD_COUNT];
  MyClass object;
  for (int i = 0; i < THREAD_COUNT; i++)
    pthread_create(&thread[i],
      NULL,
      (void*)object.my_method,
      (void*)&i);

  for (int i = 0; i < THREAD_COUNT; i++) {
    pthread_join(thread[i], NULL);
  }

  return 0;
}


after compilation i get the following error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:11: error: invalid use of member (did you forget the ‘&’ ?)

does anyone know what i'm doing wrong and how to fix it?
Mar 18, 2009 at 2:14pm
declare my_method function as this:

(void *)(*my_method)(void *);

and then compile it. It should work.
Mar 18, 2009 at 2:20pm
is there another way of doing it? i need my_method to stay the way it is.
Mar 18, 2009 at 2:42pm
As far as I know you can't do it any other way. Because the function that is required by pthread_create has to have that type.

One other way that you can do is:

create a local function in you main

1
2
3
4
5
MyClass object;
(void*)(*start)(void *)
{
     object.my_method();
}


This is like fooling around with pthread_create.
Mar 18, 2009 at 5:50pm
this wont work. send the address of the function. do this way:

1
2
MyClass object;
pthread_create(&thread[i], NULL, (void*)&object, (void*)&i);


in thread function do this:

1
2
MyClass *object = (MyClass*)param; //param is the parameter of thread function which will catch object
param->my_method();

Mar 18, 2009 at 8:41pm
That won't work either. The third parameter to pthread_create is the main function to call.
Mar 19, 2009 at 8:08am
Im extremely sorry.. :(

didnt see the signatures of pthread_create:
it will be this way:

lets say you have a thread function:
void* MainThread(void *p_param);

1
2
MyClass object;
pthread_create(&thread[i], &object, MainThread, (void*)&i);


now this will run function "MainThread".
in the function what you can do is:
1
2
3
4
5
6
void* MainThread(void *p_param)
{
MyClass *object = (MyClass *)p_param;
object->my_method();

}


if you want to call a class member make it static and then you can call.

MyClass.h file

1
2
3
4
5
6
7
8
9
class MyClass {
  public:
    static void* my_method(void *p_param);
}

void main()
{
pthread_create(&thread[i], NULL, MyClass::my_method, (void*)&i);
}


Mar 19, 2009 at 9:50am
well i guess that is what I had written. :P
Mar 19, 2009 at 10:11am
rachit:

the difference is between static and non static member. I think a non static member wont work.
Topic archived. No new replies allowed.