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

时间:2021-03-16 11:47:13   收藏:0   阅读:0

在类成员函数中如何调用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函数

示例:

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

void * Thread::ThreadRoutine(void *arg){
	Thread* thread = static_cast<Thread*>(arg);
	thread->Run();
	return NULL:
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!