我已经搜索了很多小时来寻找解决方案,但找不到简单的答案。 我有一个类,它使用 pthreads。实际的函数指针在类中是静态的,我需要锁定互斥体,因为到目前为止我得到了“奇怪”的结果(参数未正确传递)。
然而,pthread_mutex_lock 和 unlock 不会在给定线程的函数内工作,因为它在静态成员函数中,但我不能拥有非静态函数,因为它不会在类内部工作,而且我无法移动它在类之外,因为它将无法访问所需的信息。
下面的代码应该解释一下:
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();
};
和cpp文件:
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 );
}
如果有人能对此有所启发,我将不胜感激。我已经被困了几个小时了,我找不到任何信息。 谢谢!
最佳答案
“不起作用”我假设你的意思是它不会编译,因为你试图在 static
成员函数中使用实例成员。
但更大的问题是您为什么要为此使用线程?
无论如何,您拥有的线程函数完全受互斥量保护 - 您只需调用
即可获得相同(或更好)的性能a.execute(a.uniform);
b.execute(b.uniform);
而不是启动线程然后等待它们完成。
但是如果您真的想使用线程(也许您正在学习它们)并且您希望您的静态成员函数能够处理实例成员,这里有一些建议。要让它工作,您需要以某种方式将 Fight 对象的实例传递给 static
线程函数:
// somewhere in `class Fight` definition:
//
// a structure that will let you pass a Fight* instance pointer
// along with an Individual* to work on in the the
// thread function
struct context {
Fight* me;
Individual* indiv;
};
// ...
// in Fight::thread_round():
// package up data to pass to the thread function
context one = {this, &a }; // instead of Individual *one = &a;
context two = {this, &b }; // instead of Individual *two = &b;
最后,Fight::thread_run_fighter()
:
void *Fight::thread_run_fighter(void *temp)
{
// pull out the Fight object instance and the Individual
// object to work on
context* ctx = (context*) temp;
Individual *indiv = ctx->indiv;
Fight* me = ctx->me;
// do the work (in a pretty serialized fashion, unfortunately)
pthread_mutex_lock( &me->thread_mutex );
indiv->execute(indiv->uniform);
pthread_mutex_unlock( &me->thread_mutex );
return 0;
}
关于c++ - 如何在类中使用 pthread_mutex 及其函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6119664/