I have this code:
fn main() {
let mut total: i64 = 0;
let pool = ThreadPool::with_name("search worker".to_owned(), num_cpus::get());
let items = getItems(); // returns a vector of sorts
let client = blocking::Client::new();
for item in items {
let t_client = client.clone(); // must clone here for some reason
let mut took: i64 = 0;
pool.execute(move || {
took = worker(t_client);
total += took;
});
}
println!("{}", total);
}
fn worker(c: blocking::Client) -> i64 {
// do some stuff and return a value
// for sake of an example, return 25
25
}
I had to use the move
clause in the call to execute.
The problem is that the value of the total
variable remains zero. It looks like it's being duplicated inside that loop and the local variable does not get modified at all.
I do get a warning on took = worker(t_client);
and on total_took += took;
which is that those variables aren't never read.
I ended up "solving" this by making that variable static and using unsafe
, but that's not a solution. Also, eventually I need to get more results from that worker function and if I put a reference to a variable, it tell me that I can't borrow more than once, which I don't really understand.