简体   繁体   English

从pthread_create()调用函数时出错

[英]Error while calling function from pthread_create()

I have declared a function in the Class definition inside a header file: 我在头文件中的类定义中声明了一个函数:

class A
{
   public:
   ...
   void* func(void *);
   ...
}

In a .C file, I've a pointer to the class A's object as ptr. 在.C文件中,我将指向类A的对象的指针作为ptr。

Now, when i create a pthread: 现在,当我创建一个pthread时:

iret1 = pthread_create(&thread1, NULL, ptr->func, NULL);

It throws an error as: error: a pointer to a bound function may only be used to call the function. 它会引发以下错误: 错误:绑定函数的指针只能用于调用该函数。

But when I declare the function func as static, this error doesn't come. 但是,当我将func函数声明为静态函数时,不会出现此错误。

I just want to know a workaround for this as I can't change the function to static since I can't call other non-static members from it. 我只是想知道一种解决方法,因为我无法从函数中调用其他非静态成员,因此无法将其更改为静态。

You can't use non-static member functions as thread functions, or as functions to any non-C++ function expecting a function pointer. 您不能将非静态成员函数用作线程函数,也不能用作任何需要函数指针的非C ++函数的函数。 The reason is that all non-static member function has a hidden first argument that becomes the this pointer. 原因是所有非静态成员函数都有一个隐藏的第一个参数,该参数成为this指针。

In this case it can be solved with a static proxy-function: 在这种情况下,可以使用静态代理功能解决:

class A
{
public:
    void* func();

    static void* wrapper(void* object)
        { return reinterpret_cast<A*>(object)->func(); }
};

...

A* ptr = new A;
iret1 = pthread_create(&thread1, NULL, &A::wrapper, ptr);

This will create the thread with A::wrapper as the thread function, and pass the instance pointer as argument. 这将使用A::wrapper作为线程函数创建线程,并将实例指针作为参数传递。 The A::wrapper function then uses this argument as a pointer to the instance, and calls the real function. 然后, A::wrapper函数使用此参数作为实例的指针,并调用实函数。


However, if you have a C++11 capable compiler and standard library, there are much better support for threads : 但是,如果您具有支持C ++ 11的编译器和标准库,则可以更好地支持线程

A myA;
std::thread myThread(&A::func, &myA);

The above object creation creates a thread that will call A::func and pass the hidden first argument to the function as it needs. 上面的对象创建创建了一个线程,该线程将调用A::func并将隐藏的第一个参数根据需要传递给该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM