async-scoped icon indicating copy to clipboard operation
async-scoped copied to clipboard

Support for spawn_blocking

Open kodieg opened this issue 3 years ago • 3 comments

Hi,

I found your crate and I think it is very useful, however, I'd like to spawn a blocking future using spawn_blocking. Would it be possible to add spawn_blocking function to Scope?

Thanks!

kodieg avatar Oct 12 '22 08:10 kodieg

Could you explain your requirement a bit more? I see a spawn_blocking function in the tokio and async-std executors, but they seem to take a function, not a future. An example usage of the new feature would be very nice.

rmanoka avatar Oct 15 '22 11:10 rmanoka

I wanted to spawn_blocking task but without requirement of 'static closure, something similar to scoped thread, but run on blocking thread pool. I didn't think really deeply if there is anything inherently wrong with this idea.

I had in mind something like that:

let a = 42;
unsafe {
    let s = scope(|s| {
        // closure is not static, so I cannot use  
        s.spawn_blocking(|| some_blocking_fn(&a));
    });
   // do some more work
   s.await
}

It is unsafe obviously because if not awaited it is UB, but I think if awaited, then this should be safe?

Actually I'm not sure if this would do what I really need, i.e. that it would spawn task immediately and not on s.await point. Maybe there is other solution to my problem that you know of?

kodieg avatar Oct 18 '22 06:10 kodieg

@kodieg Got it. I've tried adding this support for tokio. Can you check it out?

It should work with async-std too, but I couldn't upgrade to latest async-std due to some compile error.

Edit: it also works with async-std. I must've missed something trivial.

rmanoka avatar Oct 18 '22 08:10 rmanoka

Sorry for long reply! This looks great! I tested it on tokio rt and worked fine for me!

kodieg avatar Nov 16 '22 21:11 kodieg

release 0.7.1

rmanoka avatar Nov 17 '22 07:11 rmanoka