bytedance/monoio

[Draft] Scoped Future

ethe opened this issue · 0 comments

ethe commented

Motivation

In current, monoio::spawn requires Future and its output must be 'static. However, user maybe takes lots of needless overhead (such as Rc to those captured objects) to promise 'static. If we consider the Future: ?Send + ?Sync requirment of monoio::spawn, removing the 'static requirement should be possible, because the lifetime of JoinHandle is able to be explicit and it can not be shared between threads. It is something like the future version of scoped-threads.

Advantages

Scoped-future allows user use reference (&'future _ / &'future mut _) rather than Rc or Rc<RefCell<_>> to those object which are captured in async block, it is useful to reduce the runtime overhead in some perfomance-sensitive cases.

Possible Design

Add scoped_spawn function and it returns ScopedJoinHandle:

pub fn scoped_spawn<'future, T>(future: T) -> ScopedJoinHandle<'future, T::Output>
where
    T: Future + 'future,
    T::Output: 'future,

ScopedJoinHandle must be awaited or setted canceled in lifetime. In first case, maybe we are able to use #[must_use] lint to suggest users, and force deallocate the raw task in <ScopedJoinHandle as Drop>::drop in second case to prevent data race.