C++:如何将类成员函数传递给pthread_create()?

1
2
3
4
5
6
class Task
{
public:
void * execute();
static void * threadFunc(void *);
};
  • 非静态成员函数传递给pthread_create()

  • 编译器将class(this指针)的指针作为每个成员函数中的第一个参数传递。因此,将指向类Task的对象的指针作为参数传递

    1
    2
    3
    4
    5
    6
    7
    typedef void * (*THREADFUNCPTR)(void *);
    // Pointer to object of class Task
    Task * taskPtr = new Task();
    //Thread ID
    pthread_t threadId;
    // Create thread using memeber function as startup routine
    pthread_create(&threadId, NULL, (THREADFUNCPTR) &Task::execute,taskPtr);
  • 将静态成员函数传递给pthread_create()

  • 由于静态函数与任何对象都没有关联,因此编译器不会将此指针传递给它。所以,我们不需要传递任何指针作为参数。只是传递NULL即

    1
    2
    3
    typedef void * (*THREADFUNCPTR)(void *);
    // Create pthread using static function as startup routine
    pthread_create(&threadId, NULL, (THREADFUNCPTR) &Task::threadFunc, NULL);