Hey there!
How does Rust figures out atomic reference counting is not required here?
extern crate rayon;
use rayon::prelude::*;
use std::sync::{Mutex};
fn main() {
let vec: Mutex<Vec<usize>> = Mutex::new(vec![]);
(0..100).collect::<Vec<usize>>().into_par_iter().for_each(|x| {
let mut locked = vec.lock().unwrap();
locked.push(x);
});
}
Since Rayon blocks until the parallel iteration completes, I understand that there is no need to keep track of a reference count. However, I'm not sure to understand how Rust figures this out.
I have a hunch that it's because for_each
takes a closure of type F: Fn(T) + Sync
while thread::spawn
takes a closure of type F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
.
Am I right? Could someone explain this to me?