这里又不需要把传给 t1 的 some_vec 显式转换为 ref 了,
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void f(const vector<double>& v, double* res) {
// 对v做一些操作,并将结果存储在res指向的位置
double sum = 0.0;
for (auto ele : v) {
sum += ele;
}
*res = sum;
}
class F {
public:
F(const vector<double>& vv, double* p) : v(vv), res(p) {}
void operator()() {
// 对v做一些操作,并将结果存储在res指向的位置
double sum = 0.0;
for (auto ele : v) {
sum += ele;
}
*res = sum;
}
private:
const vector<double>& v; // 输入数据源
double* res; // 存储输出结果的目标位置
};
int main() {
vector<double> some_vec{1.5, 2.5, 3.5};
vector<double> vec2{4.5, 5.5, 6.5};
double res1 = 0.0;
double res2 = 0.0;
thread t1{f, some_vec, &res1}; // 在单独线程中调用f(some_vec, &res1)
thread t2{F{vec2, &res2}}; // 在单独线程中调用F{vec2, &res2}()
t1.join();
t2.join();
cout << "res1: " << res1 << ", res2: " << res2 << '\\n';
return 0;
}