rmanoka / async-scoped

A scope for async_std and tokio to spawn non-static futures
117 stars 14 forks source link

Support for spawn_blocking #12

Closed kodieg closed 1 year ago

kodieg commented 1 year ago

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!

rmanoka commented 1 year ago

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.

kodieg commented 1 year ago

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?

rmanoka commented 1 year ago

@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.

kodieg commented 1 year ago

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

rmanoka commented 1 year ago

release 0.7.1