如何用pthreads多线程类成员函数? [英] How to multithreading a class member function with pthreads?
问题描述
我试图在多线程中从名为 SVAnchor
的类运行名为 extensionStep
的函数。我使用这个代码:
rc = pthread_create(& threads [i],NULL,extensionStep,& td [i] );
来调用函数,这里是 extensionStep
:
void * SVAnchor :: extensionStep(void * threadarg)
,我收到以下错误:
错误:不能将'SVAnchor :: extensionStep'从类型'void *(SVAnchor ::)(void *)'转换为类型'void *(*)(void *)''
rc = pthread_create(& threads [i ],NULL,extensionStep,& td [i]);
^
显示问题是从类型'void *(SVAnchor::) (void *)'to type'void *()(void)'
如何解决这个问题?
感谢所有
解决方案这应该做的工作:(在使函数
extensionStep
static)rc = pthread_create(& threads [i],NULL,&(SVAnchor :: extensionStep ),& td [i]);
或者您可以创建如下的包装函数:
struct Argument {
SVAnchor * ptr;
int * tid;
}
static void * extensionStepWrapper(void * arg)
{
return(((Argument *)arg) - > ptr) - & ((Argument *)arg)→tid);
}
并使用包装器:
参数arg;
arg.ptr =&(class_variable_name); //使用适当的名称(无论你的变量名是类SVAnchor的对象)
arg.tid =&(td [i]);
rc = pthread_create(& threads [i],NULL,&(SVAnchor :: extensionStepWrapper),& arg);
请注意,如果你从另一个成员函数中调用它,你可以这样做: / p>
arg.ptr = this;
您还可以在类中创建一个方法来启动线程:
bool StartThread(int * tid){
return(pthread_create(& _thread,NULL,extensionStep,tid)== 0);
}
您可能还需要将线程作为StartThread()函数的参数传递。
I'm trying to run a function named
extensionStep
from a class namedSVAnchor
in multi threads. i use this code:rc = pthread_create(&threads[i], NULL, extensionStep, &td[i]);
to call the function and here is the definition of
extensionStep
:void* SVAnchor::extensionStep( void *threadarg)
and i got the following error:
error: cannot convert 'SVAnchor::extensionStep' from type 'void* (SVAnchor::)(void*)' to type 'void* (*)(void*)' rc = pthread_create(&threads[i], NULL, extensionStep, &td[i]); ^
that shows the problem is converting from type 'void* (SVAnchor::)(void*)' to type 'void* ()(void)'
How to solve this problem?
Thanks all
解决方案This should do the job: (After making the function
extensionStep
static)rc = pthread_create(&threads[i], NULL, &(SVAnchor::extensionStep), &td[i]);
Or you can create a wrapper function like this:
struct Argument { SVAnchor* ptr; int* tid; } static void *extensionStepWrapper(void *arg) { return (((Argument*)arg)->ptr)->extensionStep(((Argument*)arg)->tid); }
And use the wrapper:
Argument arg; arg.ptr = &(class_variable_name); // Use appropriate name (whatever you variable name is for the object of the class SVAnchor) arg.tid = &(td[i]); rc = pthread_create(&threads[i], NULL, &(SVAnchor::extensionStepWrapper), &arg);
Note that if you're calling this from inside another member function, you may do this instead:
arg.ptr = this;
You can also create a method in the class to start the thread:
bool StartThread(int* tid){ return (pthread_create(&_thread, NULL, extensionStep, tid) == 0); }
You might also need to pass the thread as argument of StartThread() function.
这篇关于如何用pthreads多线程类成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!