在C++类中使用pthread实现多线程

现在pthread的api已经相当完善,使用其实现多线程难度不大,但是值得注意的一点是当想在类中使用pthread,调用pthread_create函数时,传入的运行函数,也就是下面这个原型的第三个参数void * ( * start_routine) (void *),如果是类的成员函数,必须是静态函数,否则将编译不通过,编译器会出一个这种错误。因为类的this指针在多线程下操作的问题,非静态的成员函数是不被允许传入的。

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                            void *(*start_routine) (void *), void *arg);

‘void*’ to ‘void* (*)(void*)’ c++?

这里只能使用静态函数将带来一个问题,静态成员函数无法访问非静态的成员,这将带来许多不便,总不能将要用到的成员变量也改成静态的,这是不推荐的。我个人使用的是一种类似跳板的方式来解决。
首先这是一个pthread_create函数:

pthread_create(&thread, NULL, &test, (void *)this);

接下来是test函数的实现,function即为自己真正要执行的函数,这样就解决了需要访问非静态成员的问题。当然如果要传的参数比较多,自己写一个struct传递就行了。

static void *test(void * arg) {
    return static_cast<ClassName *>(arg)->function();
}

另外,也可以用标准库的thread,效率上个人认为是差不多的,不过thread是可以跨平台的。

std::thread thread(&test, this);

参考:
https://stackoverflow.com/questions/12006097/cannot-convert-voidmyclassvoid-to-voidvoid-in-pthread-create-fu

发布了78 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43778179/article/details/104987307