source: example/maybe-await.rs@ ce691d2

ADT ast-experimental
Last change on this file since ce691d2 was 716b62c, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added rust and cpu example.

  • Property mode set to 100644
File size: 1.4 KB
Line 
1use futures::executor::block_on;
2use futures::future::Future;
3use std::pin::Pin;
4use std::sync::{Arc,Mutex};
5use std::task::{Context, Poll, Waker};
6
7
8struct FutureState {
9 set: bool,
10 waker: Option<Waker>,
11}
12
13#[derive(Clone)]
14struct MyFuture {
15 state: Arc<Mutex<FutureState>>
16}
17
18impl MyFuture {
19 fn new() -> MyFuture {
20 MyFuture{
21 state: Arc::new(Mutex::new(FutureState{
22 set: false,
23 waker: None
24 }))
25 }
26 }
27
28 fn fulfill(&self) {
29 let mut state = self.state.lock().unwrap();
30 state.set = true;
31 if let Some(waker) = state.waker.take() {
32 waker.wake()
33 }
34 }
35}
36
37impl Future for MyFuture {
38 type Output = ();
39 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
40 println!("Polling Future");
41 let mut state = self.state.lock().unwrap();
42 if state.set {
43 println!("Ready");
44 Poll::Ready(())
45 } else {
46 println!("Pending");
47 state.waker = Some(cx.waker().clone());
48 Poll::Pending
49 }
50 }
51}
52
53async fn hello_world(f1: MyFuture, f2: MyFuture) {
54 println!("Enter");
55 f1.await;
56 println!("Between");
57 f2.await;
58 println!("Done");
59}
60
61fn main() {
62 block_on(async {
63 let f1 = MyFuture::new();
64 let f2 = MyFuture::new();
65 let f3 = MyFuture::new();
66 let future = hello_world(f1.clone(), f2.clone());
67
68 println!("Before first fulfill");
69 f1.fulfill();
70 println!("Before second fulfill");
71 f2.fulfill();
72 println!("Before first await");
73 future.await;
74 println!("Before second await");
75 // future.await;
76 });
77}
Note: See TracBrowser for help on using the repository browser.