Class Test{
int value;
static void* thread_func(void* args){
value++;
}
void newthread(){
pthread_create(&thread_func,...);
}
}
I’m trying to create a thread in Class Test. Therefore compiler forces me to make thread_func static. However I cannot access the non-static member “value” anymore. It says:
invalid use of member 'Class::value' in static member function
Is there a way around it?
That is because
staticfunction in your class doesn’t have (and cannot have )thispointer. All you need to pass the pointer to yourTestobject to pthread_create() function as fourth argument, and then do this:However, if you’re doing too many things in
thread_func()that require access toTestclass members at many places, then I would suggest this design:Better design : define a reusable class!
Even better would be to define a reusable class with pure virtual function
run()to be implemented by the derived classes. Here is how it should be designed:Looks better?