在C++类中使用pthread实现多线程
来源:互联网 发布:php decrypt 加密 编辑:程序博客网 时间:2024/05/19 09:12
现在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
阅读全文
0 0
- 在C++类中使用pthread实现多线程
- 在VS2010中使用pthread多线程库的环境搭建
- 在C++中使用pthread
- c++中通过pthread实现多线程
- 使用pthread实现多线程CPU+GPU计算
- cocos2d-x中使用多线程--pthread
- c pthread 多线程
- 如何在QT for S60 中使用pthread库(Carbide.c++) (How to use pthread in QT4.6 for S60)
- pthread实现多线程查询
- pthread实现多线程查询
- pthread使用(多线程002)
- 不要在pthread线程中使用printf()
- C语言使用pthread多线程编程(windows系统)
- iOS中多线程的实现方案之pthread和NSThread
- Android NDK使用之--用pthread实现多线程
- linux中使用pthread和opencv多线程编程
- C语言--Linux多线程pthread
- 【Linux】【多线程】【Research_Record】pthread使用
- 详解Python的装饰器
- xpath和css选择元素的不同
- Notification 都不知道,还学什么 Android 应用开发
- 我的第一次博客
- TensorFlow 安装官方教程:Ubuntu 安装,Mac OS X 安装,Windows 安装
- 在C++类中使用pthread实现多线程
- CUDA卷积操作—使用constant memory实现高斯滤波
- HDU2066 最短路spfa 多起点 多终点 基础题
- kruskal算法应用——口袋的天空
- MYSQL学习笔记(十九)使用存储过程
- java递归算法(1加到100&换汽水)
- 正则表达式的使用
- 控制反转(IoC)与依赖注入(DI)
- 非常可乐