通过引用传递参数并在函数内更新其值的正确方法



我正在用c++编写一个程序,该程序使用绑定任务队列和从队列中获取任务的线程池。线程必须在矩阵和向量之间执行操作,并将操作结果写入另一个向量。

问题是,当线程执行的函数退出时,没有向vector中写入新值。通过引用传递和更新参数的正确方法是什么?

mutex ll;
condition_variable cond;
bool stop = false;

deque<function<void()>> bind_tasks;
// initialize the vector with all zeroes
vector<double> x(n, 0.0), new_x(n, 0.0);
auto bind_submit = [&] (function<void()> f){
{
unique_lock<mutex> lock(ll);
bind_tasks.push_back(f);
}
cond.notify_all();
};

auto body = [&](int tid){
while(true){
function<void()> t = []() {return 0; };
{
unique_lock<mutex> lock(ll);
cond.wait(lock,
[&]() { return (!bind_tasks.empty() || stop); }
);
if (!bind_tasks.empty()) {
t = bind_tasks.front();
bind_tasks.pop_front();
}
if (stop)
return;
}
t();
}
};

// executed by the threads
auto f = [&](vector<vector<double>> matrix, vector<double> x,
vector<double> b, vector<double> new_x, int i, int n){
int sum = 0;
// use the values of x and writes on new_x
for (int j = i + 1; j < n; j++) {
sum = matrix[i][j] * x[j];
}
new_x[i] = (b[i] - sum) / matrix[i][i];
};
vector<thread> tids(nw);
for(int tid=0; tid<nw; tid++){
tids[tid] = thread(body, tid);
}

for(int it=0; it<k; it++){
for(int i=0; i<n;i++){
auto fx = (bind(f, matrix, x, b, new_x, i, n));
bind_submit(fx);
}
//function that prints the vector
print_vector(new_x); //it is still all zeroes

x=new_x;
}

通过引用传递参数的正确方法是drum roll实际通过引用传递参数。

auto f = [&](vector<vector<double>> matrix, vector<double> x,
vector<double> b, vector<double> new_x, int i, int n){ ... }

所有参数都是按值传递的。您还可以通过引用绑定其他所有内容,并且永远不要使用它。

我认为你误解了[&]的作用。

你的lambda不需要绑定任何东西,只需传递参数作为引用。

auto f = [](const vector<vector<double>> & matrix, const vector<double> & x,
cost vector<double> & b, vector<double> & new_x, int i, int n){ ... }

最新更新