类中pthread_create()的线程入口函数

在类成员函数中如何调用pthread_create()呢?

#incldue <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

可看到入口函数的指针是void*类型的,通过 *arg传递参数
如果线程的入口函数设置为类的函数呢?
调用类中非static函数是有this指针的
此时可通过把入口函数设置为static函数,将this指针作为参数传递过去
再在static入口函数中通过this指针调用类中非static函数

示例:

#include <pthread.h>

class Thread
{
public:
    Thread();
    vitrtual ~Thread();
    
    void Start();
private:
    static void* ThreadRoutine(void* arg);
    virtual void Run() = 0;
    pthread_t threadId_;
    
};

void Thread::Start(){
	pthread_create(&threadId_, NULL, ThreadRoutine, this);
}

void * Thread::ThreadRoutine(void *arg){
	Thread* thread = static_cast<Thread*>(arg);
	thread->Run();
	return NULL:
}
}
posted @ 2021-03-14 10:15  零十  阅读(99)  评论(0编辑  收藏  举报