fix(runtime): Box the main future to avoid blowing up the stack (#19155)

This fixes `Unhandled exception at [...] Stack overflow` on Windows,
caused by the large size of the main future.
This commit is contained in:
Matt Mastracci 2023-05-17 15:49:57 -06:00 committed by GitHub
parent 41f618a1df
commit 62e779f82d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 130 additions and 93 deletions

View file

@ -16,14 +16,26 @@ pub fn create_basic_runtime() -> tokio::runtime::Runtime {
.unwrap()
}
#[inline(always)]
pub fn create_and_run_current_thread<F, R>(future: F) -> R
where
F: std::future::Future<Output = R> + 'static,
R: Send + 'static,
{
let rt = create_basic_runtime();
// Since this is the main future, we want to box it in debug mode because it tends to be fairly
// large and the compiler won't optimize repeated copies. We also make this runtime factory
// function #[inline(always)] to avoid holding the unboxed, unused future on the stack.
#[cfg(debug_assertions)]
// SAFETY: this this is guaranteed to be running on a current-thread executor
let future = Box::pin(unsafe { MaskFutureAsSend::new(future) });
#[cfg(not(debug_assertions))]
// SAFETY: this this is guaranteed to be running on a current-thread executor
let future = unsafe { MaskFutureAsSend::new(future) };
let join_handle = rt.spawn(future);
rt.block_on(join_handle).unwrap().into_inner()
}