I have a general struct
with settings and an extra variable setting that I want to tune and play around with.
For all possible values in an integer ra
Yes, it is possible to move only one or some variables into a closure (rather than all or none).
Yes, this can be used to "circumvent" reference counting.
I found an answer in the documentation of rayon::scope that turns out to be exactly about this problem: 'Accessing the stack data [from within a scoped threads scope]'. That page also has an example that is clearer than the pseudocode in this question.
It turns out that you can either:
Use a move
closure but refer to variables in the outer scope by shadowing them with a reference, therefore capturing them by reference rather than by value, using let settings = &settings
:
crossbeam::scope(|scope| {
let settings = &settings; // refer to outer variable by reference
for score in 0..MAX_FEASIBLE_SCORE {
scope.spawn(move |_| {
let work_result = do_cool_computation(settings, score);
println!("{:?}", work_result);
});
}
})
.unwrap();
Use a normal closure, and only move the required variables by shadowing them inside the closure using let score = score
:
crossbeam::scope(|scope| {
for score in 0..MAX_FEASIBLE_SCORE {
scope.spawn(|_| {
let score = score; // capture only score
let work_result = do_cool_computation(&settings, score);
println!("{:?}", work_result);
});
}
})
.unwrap();