如何通过调用类中的函数来创建线程? [重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过调用类中的函数来创建线程? [重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
假设有
class concurr{
public:
double arr[100];
void func1(vector<vector<double>> data,int x);
double func2(vector<vector<double>> data);
}
这样func2接收“数据”并用相同的“数据”将其提供给func1,但是从0到100再到x的不同数量。然后在func1中,它计算出一些东西,无论它出现的是什么值,为arr填充它[x]所以基本上,func2看起来很像
double concurr::func2(vector<vector<double>> data){
thread threads[100];
for (int x = 0; x < 100; x++){
threads[x] = thread(concurr::func1,data,x); // this line is where the problem is
}
for (auto& th : threads){
th.join();
}
// ..... does something with the arr[100].... to come up with double = value
return value;
}
没有多线程部分,代码运行良好,只是通过添加多线程部分,当我尝试编译时,它说“必须调用对非静态成员函数的引用”
答案
使用线程调用成员函数时,您需要传递类的对象或引用它(在您的情况下):
threads[x] = thread(concurr::func1, *this,data,x);
或者使用lambda
threads[x] = thread( [&]{ this->func1(data, x); } )
以上是关于如何通过调用类中的函数来创建线程? [重复]的主要内容,如果未能解决你的问题,请参考以下文章
在派生构造函数中的某些代码块之后调用派生类中的基类构造函数[重复]