Scoped threads?

So we have this weird idea and would like to talk to ppl before trying to do it. Rust used to have scoped threads a long time ago, but they were very unsound because reasons. Some alternatives have popped up since, but they all use the "run a closure to force drop" option. It's not a bad option tbh, but we wanna do something slightly different: delay the threads until drop.

The API would look roughly like:

fn scope<'a>() -> ScopeGuard<'a>;

impl ScopeGuard<'a> {
  fn add_thread(&mut self, f: impl Fn() + 'a);
  fn set_main_thread(&mut self, f: impl Fn(&mut Self) + 'a);
}

Rather than spawning the threads as soon as add_thread is called, the threads would just be collected and queued up instead. The Drop impl would then spawn the threads and call the "main thread", and any future calls to add_thread (from inside the main thread) would immediately spawn extra threads. These are about the best (or arguably worst) tradeoffs we can think of between the original scoped threads and modern crossbeam scoped threads and whatnot. Thoughts?

2 Likes

This is basically the design behind the easy-parallel crate. It has a slightly more powerful API than yours because it supports returning values from the functions.

Hm, not quite - that one doesn't use Drop. :stuck_out_tongue:

That is easy-parallel ?