Firstly... even if this "worked" your code would be broken because run is being accessed by multiple threads and accesses are not guarded. You will need to either make it atomic, or put accesses to it behind a mutex or else you will have race conditions.
That said...
pthread_create requires you give it a function with exactly 1 parameter: a
void*
.
The problem is... member functions require a hidden "this" parameter to indicate which object the function operates on. Therefore Foo::task1 actually requires 2 parameters...
this
and
void*
. Therefore you can't pass it to pthread_create because the parameters don't match what is required.
Static members do not require a this parameter, so you could make task1 and task2 static... which will fix the problem. The side-effect being, of course, that the functions will now be static and will not have a this parameter, and therefore will be unable to access non-static members (like 'run').
Typically what is done here... is the void* parameter you give pthread_create is used to pass a pointer to the object to use as 'this'. So you could do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Foo
{
//...
void* task1()
{
// ...
}
static void* task1_launch(void* object)
{
Foo* obj = reinterpret_cast<Foo*>(object);
return obj->task1();
}
//...
// when creating the thread:
pthread_create(&thread1, NULL, &Foo::task1_launch, this); // <- pass 'this' as the object
};
|
Of course... its probably easier to use C++ standard lib threads rather than pthreads anyway.