mirror of
https://github.com/guilhermewerner/mini-redis
synced 2025-06-16 06:55:01 +00:00
Implement Some Tokio Tutorials
This commit is contained in:
48
Tutorial/Waker.rs
Normal file
48
Tutorial/Waker.rs
Normal file
@ -0,0 +1,48 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Delay {
|
||||
when: Instant,
|
||||
}
|
||||
|
||||
impl Future for Delay {
|
||||
type Output = &'static str;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> {
|
||||
if Instant::now() >= self.when {
|
||||
println!("Hello world");
|
||||
Poll::Ready("done")
|
||||
} else {
|
||||
// Get a handle to the waker for the current task
|
||||
let waker = cx.waker().clone();
|
||||
let when = self.when;
|
||||
|
||||
// Spawn a timer thread.
|
||||
thread::spawn(move || {
|
||||
let now = Instant::now();
|
||||
|
||||
if now < when {
|
||||
thread::sleep(when - now);
|
||||
}
|
||||
|
||||
waker.wake();
|
||||
});
|
||||
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let when = Instant::now() + Duration::from_millis(100);
|
||||
let future = Delay { when };
|
||||
|
||||
let out = future.await;
|
||||
assert_eq!(out, "done");
|
||||
}
|
Reference in New Issue
Block a user