如何修复此Pthread示例中的错误?

fsi*_*idi 0 c++ pthreads

我做了所有必要的配置,比如包括Pthread库和头文件......

错误是:

error C3867: 'FunctionClass::calledfunction': function call missing argument list; use '&FunctionClass::calledfunction' to create a pointer to member
Run Code Online (Sandbox Code Playgroud)

这是导致错误的示例:

class FunctionClass
{

 public:

    void * calledfunction( void *);
    /*
    this is the definition of the function in the FunctionClass.cpp
    void * FunctionClass::calledfunction( void *)
    {
        //do sth;
    }

    */


};

int main(void)
{

pthread_t process_m;
FunctionClass *obj = new FunctionClass ();

int nbr= 5;

if(pthread_create(&process_m,NULL,obj->calledfunction,(void *)nbr)< 0)
    {
        std::cout << "thread1";

}
 }
Run Code Online (Sandbox Code Playgroud)

什么可能导致错误?我尊重函数pthread_create的语法......但是我找不到这个错误的原因!

peo*_*oro 5

您不能使用非静态成员函数作为回调.

使用自由函数或静态成员函数作为第三个参数pthread_create.


编辑以反映OP的评论:

如果需要FunctionClass为特定FunctionClass对象调用函数成员(obj在您的示例中),常见的方法是调用静态成员函数(或自由成员函数)将对象传递给它,然后从那里调用对象的成员函数.

这是一个例子(没有测试它,但它应该让你明白该做什么):

struct obj_arg_pair { FunctionClass *obj; int nbr; };
static void * calledfunctionStatic( void *args_ )
{
    obj_arg_pair *args = reinterpret_cast< obj_arg_pair * >( args_ );
    return args->obj->calledFunction( args->nbr );
}
Run Code Online (Sandbox Code Playgroud)

然后使用与此类似的代码启动您的线程:

obj_arg_pair args;
args.nbr = 5;
args.obj = obj;
pthread_create(&process_m,NULL,FunctionClass::calledfunction,(void *)&args);
Run Code Online (Sandbox Code Playgroud)