rayon: Using rayon under a Mutex can lead to deadlocks
https://users.rust-lang.org/t/using-rayon-in-code-locked-by-a-mutex/20119
@kornelski presented the following pseudo-code representing a possible deadlock:
fn mutex_and_par() {
some_mutex.lock().par_iter().collect();
}
collection.par_iter().for_each(mutex_and_par);
I think the way this fails is something like:
- Thread 1 starts processing one of the
for_each(mutex_and_par)calls.- grabs the lock
- splits up the
par_iter()into a few jobs - starts the
collect()on one of those jobs
- Another thread steals one of those jobs to help out
- Thread 1 finishes its current job
- looks for the other jobs and sees they’re stolen elsewhere
- goes to steal more work itself while it’s waiting…
- finds another of the
for_each(mutex_and_par)calls - tries to grab the lock (again) … DEADLOCK
If serialized, this code would never be a problem, but a work-stealing threadpool can cause it to implicitly recurse the lock. I’m not sure what we can do about this, or if there’s any better advice we can give than just “don’t call rayon under a mutex”…
About this issue
- Original URL
- State: open
- Created 8 years ago
- Reactions: 1
- Comments: 15 (13 by maintainers)
If this isn’t going to be fixed, I would suggest documenting it as a known issue and adding a warning to
par_*documentation.I just spent nearly two hours debugging a dead-lock before finding this issue 😢
I was able to get something like this working by adding a feature for
full_blockingthread pools. This prevents the https://github.com/rayon-rs/rayon/pull/449 behavior when a pool is created with thefull_blockingfeature.See for more details: https://github.com/rayon-rs/rayon/pull/1175
That use would still be a deadlock-loop if the lock holder – or anything the lock holder is waiting for – is blocked by you on the call stack. They’ll never complete until you return to them.
I think this is feasible.