Runs f on a thread of its own and is done when f is: for work that blocks (a request with a blocking client, a file) in an app with no async runtime. If f panics the future never ends. Not in a browser, which has no threads to give.
The thread starts at once; the future is ready when it is done, and wakes the app's runner from the thread.
Signature
pub fn blocking<T: Send + 'static>( f: impl FnOnce() -> T + Send + 'static, ) -> impl Future<Output = T> + 'staticExample
use fusuma::blocking;
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct Nobody;
impl Wake for Nobody {
fn wake(self: Arc<Self>) {}
}
let waker = Waker::from(Arc::new(Nobody));
let mut cx = Context::from_waker(&waker);
let mut future = pin!(blocking(|| 6 * 7));
let answer = loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
break value;
}
std::thread::yield_now();
};
assert_eq!(answer, 42);