Skip to content

async-std

channel

1
2
3
chrono = "0.4.19"
futures = "0.3.8"
async-std = { version = "1.8.0", features = ["attributes"] }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use chrono::prelude::*;
use futures::channel::mpsc::unbounded;
use async_std::task;
use futures::StreamExt;
use async_std::task::sleep;
use std::time::Duration;

#[async_std::main]
async fn main() {
    let (tx, mut rx) = unbounded::<i32>();
    task::spawn(async move {
        while let Some(msg) = rx.next().await {
            sleep(Duration::from_secs(3)).await;
            println!("now = {} msg = {}", Local::now(), msg);
        }
    });
    println!("send time = {}", Local::now());
    tx.unbounded_send(1).ok();
    tx.unbounded_send(2).ok();
    sleep(Duration::from_secs(10)).await;
}

输出结果:

1
2
3
send time = 2020-12-27 19:13:47.358795165 +08:00
now = 2020-12-27 19:13:50.359123955 +08:00 msg = 1
now = 2020-12-27 19:13:53.359470781 +08:00 msg = 2

block_on

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use async_std::task;
use std::time::Duration;
use chrono::Local;
use std::rc::Rc;
use std::cell::RefCell;

async fn say_hello(val: Rc<RefCell<i32>>) {
    task::sleep(Duration::from_secs(2)).await;
    *val.borrow_mut() += 10;
}

fn main() {
    let val = Rc::new(RefCell::new(10));
    println!("start time = {}", Local::now());
    task::block_on(say_hello(Rc::clone(&val)));
    println!("{}", *val.borrow());
}

输出结果:

1
2
start time = 2021-05-13 14:17:25.258462050 +08:00
20

spawn_local

1
2
3
async-std = { version = "1.9.0", features = ["unstable"] }

chrono = "*"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use async_std::task;
use std::time::Duration;
use chrono::Local;
use std::rc::Rc;
use std::cell::RefCell;

async fn hello_world1(val: Rc<RefCell<i32>>) {
    task::sleep(Duration::from_secs(2)).await;
    *val.borrow_mut() += 10;
    println!("hello world1!, {}", Local::now());
}

async fn hello_world2() {
    task::sleep(Duration::from_secs(3)).await;
    println!("hello world2!, {}", Local::now());
}

async fn say_hello() {
    let val = Rc::new(RefCell::new(10));
    task::spawn_local(hello_world1(Rc::clone(&val)));
    hello_world2().await;
    println!("{}", *val.borrow())
}

fn main() {
    println!("start time = {}", Local::now());
    task::block_on(say_hello());
}

输出结果:

1
2
3
4
start time = 2021-05-13 10:55:40.405499007 +08:00
hello world1!, 2021-05-13 10:55:42.416584960 +08:00
hello world2!, 2021-05-13 10:55:43.416487988 +08:00
20