This is less of a question and more of a discovery which I thought might be useful to others. Given:
struct Foo { ... }
impl Foo {
fn action(&mut self) { ... }
}
The following will not deadlock:
fn it_wont_deadlock() {
let foo = Arc::new(Mutex::new(Foo { value: 0 }));
(0..10).into_par_iter().for_each_with(foo, |f, _| {
f.lock().unwrap().action(); // Lock immediately dropped here.
f.lock().unwrap().action();
}
}
But this sure will!
fn deadlock() {
let foo = Arc::new(Mutex::new(Foo { value: 0 }));
(0..10).into_par_iter().for_each_with(foo, |f, _| {
let lock = f.lock().unwrap();
f.action();
f.lock().unwrap().action();
}
}
The former behaviour was a surprise to me, I thought the lock would stick around until the end of the block, even though I never assigned it.