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

问题描述 投票:0回答:1

这个问题在这里已有答案:

假设有

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

没有多线程部分,代码运行良好,只是通过添加多线程部分,当我尝试编译时,它说“必须调用对非静态成员函数的引用”

c++ multithreading function c++11 concurrency
1个回答
3
投票

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

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

或者使用lambda

threads[x] = thread( [&]{ this->func1(data, x); } )
© www.soinside.com 2019 - 2024. All rights reserved.