I searched many hours for a solution, but cannot find a simple answer. I have a class that uses pthreads. The actual function pointer is static in the class, and I need to lock the mutex, because so far I get "strange" results (parameters are not passed correctly).
However, pthread_mutex_lock and unlock will not work in the function specified for the thread, because it is in a static member function, but I cannot have a function that is not static, because it will not work inside the class, and I cannot move it outside the class because he will not be able to access the necessary information.
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 very grateful if anyone could shed light on this. I was stuck for several hours and I could not find any information. Thanks!