Skip to content

Instantly share code, notes, and snippets.

@tom-code
Created November 10, 2019 15:49
Show Gist options
  • Select an option

  • Save tom-code/0840a6ebce8112dd3e1ed3a5fab56421 to your computer and use it in GitHub Desktop.

Select an option

Save tom-code/0840a6ebce8112dd3e1ed3a5fab56421 to your computer and use it in GitHub Desktop.
rust async await std
// futures-executor = "0.3.1"
use std::pin::Pin;
use std::thread;
use std::time;
use std::future::Future;
use std::task::Poll;
pub struct Waiter {
state : u32,
}
impl Waiter {
pub fn new() -> Waiter {
Waiter {
state: 0
}
}
}
impl Future for Waiter {
type Output = i32;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
println!("poll");
if self.state == 0 {
unsafe {
self.get_unchecked_mut().state = self.state + 1;
}
let wk = cx.waker().clone();
thread::spawn(move || {
thread::sleep(time::Duration::from_secs(1));
wk.wake();
});
Poll::Pending
} else {
Poll::Ready(1)
}
}
}
fn main() {
println!("Hello, world!");
thread::spawn(move || {
thread::sleep(time::Duration::from_secs(1));
println!("thread")
});
let a = async {
println!("await...");
let w = Waiter::new().await;
println!("awaited {}", w);
w
};
futures_executor::block_on(a);
thread::sleep(time::Duration::from_secs(3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment