pthread function from a class(类中的 pthread 函数)
问题描述
假设我有一个类,例如
class c {
// ...
void *print(void *){ cout << "Hello"; }
}
然后我有一个 c 的向量
And then I have a vector of c
vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());
现在,我想在 c.print();
下面给了我下面的问题:pthread_create(&t1, NULL, &c[0].print, NULL);
And the following is giving me the problem below: pthread_create(&t1, NULL, &c[0].print, NULL);
错误输出:无法将‘void* (tree_item::)(void)’转换为‘void*()(void)’ 用于参数 ‘3’ 到 ‘int pthread_create(pthread_t*, constpthread_attr_t*, void* ()(void), void*)’
Error Ouput: cannot convert ‘void* (tree_item::)(void)’ to ‘void* ()(void)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’
推荐答案
你不能按照你写的方式来做,因为 C++ 类成员函数有一个隐藏的 this
参数传入.pthread_create()
不知道要使用什么 this
的值,所以如果你试图通过将方法转换为适当类型的函数指针来绕过编译器,你会出现分段错误.您必须使用静态类方法(没有 this
参数)或普通函数来引导类:
You can't do it the way you've written it because C++ class member functions have a hidden this
parameter passed in. pthread_create()
has no idea what value of this
to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this
parameter), or a plain ordinary function to bootstrap the class:
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
这篇关于类中的 pthread 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类中的 pthread 函数


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07