C++ pthread_create c++;
我有一个名为qwerty的类和一个名为compute\u ans的函数,它接受一个空指针并返回一个空指针。现在,当我尝试编译时,下面的语句抛出一个错误C++ pthread_create c++;,c++,multithreading,function-pointers,C++,Multithreading,Function Pointers,我有一个名为qwerty的类和一个名为compute\u ans的函数,它接受一个空指针并返回一个空指针。现在,当我尝试编译时,下面的语句抛出一个错误 pthread_create (thread_a, NULL, compute_ans, (void*) struct_left); 函数的定义是:void*compute\u ans(void*struct\u input) 错误是 无法将“qwerty::compute_ans”从类型“void*(qwerty::)(void*)”转换为类
pthread_create (thread_a, NULL, compute_ans, (void*) struct_left);
函数的定义是:void*compute\u ans(void*struct\u input)
错误是
无法将“qwerty::compute_ans”从类型“void*(qwerty::)(void*)”转换为类型“void*()(void)”*
你可以找到答案
应该使用静态函数传递给pthread
class qwerty
{
public:
void compute_ans(void)
{
std::cout << "Compute result!" << std::endl;
return
}
static void hello_helper(void *context)
{
return ((qwerty *)context)->compute_answer();
}
};
...
qwerty c;
pthread_t t;
pthread_create(&t, NULL, &qwerty::hello_helper, &c);
qwerty类
{
公众:
void计算(void)
{
STD::CUT< P>不能将指针转换为非静态成员函数,而不允许函数指向指针,C++不允许它。原因是成员函数采用隐式<代码>这个< /COD>指针作为参数。本质上,这会改变函数的签名,如“代码>空隙* CopyTeTeNe(QWERTY *,VATE *))。
。要将函数传递给pthread\u create
,需要将成员函数设置为静态
class qwerty
{
public:
// ... other member functions and variables ...
// thread start function
static void* compute_ans(void*);
};
如果无法将其作为静态成员函数,则需要将指向qwerty
对象的指针传递给线程启动函数。查看问题中的代码,还需要将其他数据传递给线程函数。为此,可以使用包含所有必要数据的附加数据结构并传递poin相反,我更倾向于这一点
class qwerty; // forward declaration
// Structure passed to pthread_create and our helper function
struct thread_data
{
qwerty* qptr; // pointer to qwerty object
void* data; // pointer to other data. change void to your data type.
};
class qwerty
{
public:
// thread start function
static void* start_compute_ans(void* param)
{
// get a pointer to the thread data
thread_data* tdata = static_cast<thread_data*>(param);
// Call the real compute_ans
tdata->qptr->compute_ans(tdata->data);
// Delete the data (use an appropriate smart pointer if possible)
delete tdata;
return NULL;
}
// the real
void compute_ans(void*)
{
// do stuff here
}
};
// Create our thread startup data
thread_data* tdata = new thread_data();
tdata->qptr = qwerty_pointer;
tdata->data = struct_left;
// start the thread data
pthread_create (thread_a, NULL, &qwerty::start_compute_ans, tdata);
class qwerty;//转发声明
//结构传递给pthread_create和我们的helper函数
结构线程数据
{
qwerty*qptr;//指向qwerty对象的指针
void*data;//指向其他数据的指针。将void更改为您的数据类型。
};
qwerty类
{
公众:
//线程启动函数
静态void*start\u compute\u ans(void*param)
{
//获取指向线程数据的指针
线程数据*tdata=静态线程转换(参数);
//称之为真正的计算机
tdata->qptr->计算(tdata->数据);
//删除数据(如果可能,使用适当的智能指针)
删除tdata;
返回NULL;
}
//真实的
void计算(void*)
{
//在这里做事
}
};
//创建我们的线程启动数据
线程_数据*tdata=新线程_数据();
tdata->qptr=qwerty_指针;
tdata->data=struct\u left;
//启动线程数据
pthread_create(thread_a,NULL,&qwerty::start_compute_ans,tdata);
这是一个相当长的应用程序,如果我转换上述函数,我将不得不将所有其他函数转换为静态函数或创建一个对象!!有解决方法吗?你不必这么做。我将用该场景的解决方案更新我的答案。可能需要一些时间;)哦!!等等…这是讽刺吗?!我正试图为它下决定在过去的10分钟里,我终于得出结论!!我想我应该继续做下去,然后再做更长的时间…-(不,这不是讽刺。我只是想确保一切都是正确的、可编译的和有效的。另外,我想要一个我猜错了的蛋糕!!你是认真的。这个解决方案让你@Captain动摇了