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

标签 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 接受“数据”并将其提供给 func1 相同的“数据”但 x 的数量从 0 到 100 不等。然后在 func1 中,它计算一些东西以及它的 double 值出来,为 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); } )

关于c++ - 如何通过调用类中的函数来创建线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116636/

相关文章:

c++ - C++程序优化

php - PHP 7.4.8 5.6x在类似测试(g++ 4.8.5)中比相同的c++程序快

python - 线程已完成的进程永远不会退出

ruby - 如何从 Ruby 中的线程返回值?

java - 锁和 .join() 方法之间的区别

javascript - 连接输出 - 初级函数

c++ - 为什么此分配器不适用于 `std::allocate_shared` ?奇怪的模板替换错误

c++ - 在 OS X 10.9.3 上使用 Xcode 5.1.1 编译 unordered_map 失败

azure - 部署Azure Function时ConnectionString为null

c - 在 C 中以相反的顺序传递参数有什么意义?