gpt4 book ai didi

c++ - 类中的 pthread 函数

转载 作者:IT老高 更新时间:2023-10-28 12:06:20 24 4
gpt4 key购买 nike

假设我有一个类,例如

class c { 
// ...
void *print(void *){ cout << "Hello"; }
}

然后我有一个 c vector

vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());

现在,我想在 c.print();

上创建一个线程

以下是给我以下问题:

pthread_create(&t1, NULL, &c[0].print, NULL);

Error Output: cannot convert ‘void* (tree_item::*)(void*)’ to ‘void*(*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, constpthread_attr_t*, void* (*)(void*), void*)’

最佳答案

你不能像你写的那样做,因为 C++ 类成员函数有一个隐藏的 this 参数传入。 pthread_create() 不知道是什么this 的值,所以如果你试图通过将方法转换为适当类型的函数指针来绕过编译器,你会得到一个段错误。您必须使用静态类方法(没有 this 参数)或普通函数来引导类:

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);

关于c++ - 类中的 pthread 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1151582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com