Skip to content

Instantly share code, notes, and snippets.

@Sherlock-Holo
Created February 16, 2020 11:11
Show Gist options
  • Save Sherlock-Holo/00753e0d74089f41f2412600f5a9ead5 to your computer and use it in GitHub Desktop.
Save Sherlock-Holo/00753e0d74089f41f2412600f5a9ead5 to your computer and use it in GitHub Desktop.
third runtime with tokio
// from https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fbb7daec1be993d3a4cd6f6181f332a0
use std::future::Future;
use std::pin::Pin;
use std::thread;
use futures::future::{pending, poll_fn};
use lazy_static::lazy_static;
use tokio::runtime::{Handle, Runtime};
lazy_static! {
static ref HANDLE: Handle = {
let mut rt = Runtime::new().unwrap();
let handle = rt.handle().clone();
thread::spawn(move || rt.block_on(pending::<()>()));
handle
};
}
pub async fn enter_tokio<T>(mut f: impl Future<Output = T>) -> T {
poll_fn(|context| {
HANDLE.enter(|| {
// Safety: pinned on stack, and we are in an async fn
// WARN: DO NOT use f in other places
let f = unsafe { Pin::new_unchecked(&mut f) };
f.poll(context)
})
})
.await
}
fn main() {
futures::executor::block_on(enter_tokio(async {
tokio::fs::write("x", b"xxxxxxxxx").await.unwrap();
dbg!(tokio::fs::read_to_string("x").await.unwrap());
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment