如何通过调用类中的函数来创建线程?

时间:2018-03-05 17:55:16

标签: c++ multithreading function c++11 concurrency

假设有

class concurr{
public:

double arr[100];
void func1(vector<vector<double>> data,int x);
double func2(vector<vector<double>> data);
}

这样func2接收&#34;数据&#34;并使用相同的&#34;数据&#34;将其提供给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;
    }

没有多线程部分,代码运行良好,只是添加了多线程部分,当我尝试编译时,它说 &#34;必须引用非静态成员函数       称为&#34;

1 个答案:

答案 0 :(得分:3)

使用线程调用成员函数时,需要将类的对象或引用传递给它(在您自己的情况下):

threads[x] = thread(concurr::func1, *this,data,x);

或使用lambda

threads[x] = thread( [&]{ this->func1(data, x); } )