I have searched for many hours for a solution, but cannot find an easy answer.
I got a class, which uses pthreads. The actual function pointer is static within the class, and I need to lock on a mutex, because so far I get “weird” results (parameters not being passed correctly).
However the pthread_mutex_lock and unlock will not work within the function given to the thread, because it is in a static member function, yet I cannot have the function non static because it won’t work inside the class, and I cannot move it outside the class, because it won’t be able to access required info.
The following code should explain:
class Fight{
pthread_mutex_t thread_mutex;
static void *thread_run_fighter(void *temp);
public:
Fight();
bool thread_round(Individual &a, int a_u, Individual &b, int b_u);
std::vector<Individual> tournament();
};
And the cpp file:
Fight::Fight(){
thread_mutex = PTHREAD_MUTEX_INITIALIZER;
}
bool Fight::thread_round(Individual &a, int a_u, Individual &b, int b_u){
if (a.saved and b.saved){
a.uniform = a_u;
b.uniform = b_u;
Individual *one = &a;
Individual *two = &b;
pthread_t a_thread, b_thread;
int a_thread_id, b_thread_id;
a_thread_id = pthread_create(&a_thread,NULL,Fight::thread_run_fighter,(void*) one);
b_thread_id = pthread_create(&b_thread,NULL,Fight::thread_run_fighter,(void*) two);
pthread_join( a_thread, NULL);
pthread_join( b_thread, NULL);
return true;
}
else{
return false;
}
}
void *Fight::thread_run_fighter(void *temp){
Individual *indiv;
indiv = (class Individual*)temp;
pthread_mutex_lock( &thread_mutex );
indiv->execute(indiv->uniform);
pthread_mutex_unlock( &thread_mutex );
}
I would be really grateful if anyone could shed some light into this. I have been stuck for some hours now, and I could not find any info whatsoever.
Thank you!
By ‘doesn’t work’ I assume you mean it won’t compile since you’re trying to use an instance member in a
staticmember function.But the bigger question is why are you trying to use threads for this?
The thread function you have is entirely protected by the mutex anyway – you’ll get the same (or better) performance by simply calling
instead of spinning up the threads then waiting for them to complete.
But if you really want to use threads (maybe you’re learning about them) and you want your static member function to be able to deal with instance members, here are some pointers. To get that to work, you’ll need to somehow pass an instance of the Fight object to the
staticthread function:Finally,
Fight::thread_run_fighter():