rust语言tokio库spawn, blocking_spawn等的使用


时间会遗忘一切

最后更新时间2024.04.29

tokio版本:

tokio的spawn以及spawn_blocking的使用

tokio::task::spawn方法解析

tokio的实现原理以及源码解析请移步我的另一篇博客:
我们举一个实际的例子来说明tokio::spawn的使用。我们创建一个tokio::main,指定工作线程数量为2,方便大家理解,如果不指定,则会与CPU数量相同。因为在这个例子中,我们一共有两个异步sleep,所以创建两个工作线程方便大家理解。

use tokio;

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
    let handle_1 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(10));
        println!("sleeping 10s");
    });
    let handle_2 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("second spawn!");
    });
    tokio::join!(handle_1, handle_2);
    println!("hello world!");
}

tokio::spawn方法的返回值是一个handle,如果不调用tokio::join!方法,tokio是不会将这两个handle放入工作线程中去运行的。当我们调用了tokio::join!后,相当于同时调用了handl_1.await和handle_2.await,main函数主线程会阻塞等待这两个handle执行完成。所以最终的输出结果是这样的:

# 等1s后打印
second spawn!
# 打印second spawn后,等9s后打印
sleeping 10s
# 打印sleeping 10s后立即打印
hello world!

tokio::spawn方法的返回值是一个handle,如果对这个handle执行.await方法,会阻塞当前调用这个spawn方法的线程,只有在这个handle执行完成后,才会继续执行后面的代码。如下例所示

use tokio;

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
    let _ = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(10));
        println!("sleeping 10s");
    }).await;
    let _ = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("second spawn!");
    }).await;
    println!("hello world!");
}

在该例子中,因为在主线程中,使用tokio::task::spawn创建了第一个handle_1,并调用该handle_1的.await方法,此时主线程阻塞在这里,等待handle_1执行完毕,即sleep 10s后打印sleep 10s。随后使用tokio::task::spawn创建第二个handle_2,并调用该handle_2的.await方法,此时主线程阻塞在这里,等待handle_2执行完毕,即sleep 1s后打印second spawn!。最后执行主线程中的hello world打印。

上例的输出为:

# 等10s后打印
sleeping 10s
# 打印sleeping 10s完成后等1s后打印
second spawn!
# 打印second spawn完成后立即打印
hello world!

如果我们工作线程有两个,但是我们有3个异步操作会发生什么呢?见下例:

use tokio;

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
    let handle_1 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(10));
        println!("sleeping 10s");
    });
    let handle_2 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("second spawn!");
    });
    let handle_3 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(5));
        println!("third spawn!");
    });
    tokio::join!(handle_1, handle_2, handle_3);
    println!("hello world!");
}

我们有3个异步spawn,分别睡眠10s、1s、5s。tokio::join按照写代码的顺序,先join的10s的handle_1,然后1s的handle_2,然后5s的handle_3。由于只有两个工作线程,所以10s的handle_1和1s的handle_2可以同时在两个工作线程中执行,但是handle_3不行,因为已经没有多余的工作线程可供handle_3去运行了,所以handle_3只能先挂起,并不执行。过了1s后,当handle_2的工作线程把handle_2执行完,此时这个工作线程空闲出来就可以去执行handle_3了,所以在handle_2的second spawn打印完成以后,handle_3开始执行,所以最终的输出如下:

# 等1s后打印
second spawn!
# 在second spawn打印后,等5s打印
third spawn!
# 在third spawn打印后,等4s打印
sleeping 10s
# 在sleeping 10s打印后,立即打印hello world
hello world!

tokio::task::spawn_blocking()方法解析

我们知道,当我们定义tokio的时候,可以定义工作线程的数量

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]

但是我们可以看到,在上述的例子中,如果工作线程被阻塞了,即使这个工作线程啥都不做,他也会阻塞在那里,这样CPU就开始摸鱼了,但是我们是社会主义,怎么能摸鱼呢,所以我们不能让CPU有能摸鱼的机会,那么这些阻塞的工作应该怎么办呢?这里tokio给出了一个spawn_blocking的方法。
spawn_blocking方法中的内容,不会在工作线程中运行,而是创建了一个单独的线程用来执行写在spawn_blocking方法中的内容,这样即使是写在spawn_blocking方法中的内容是阻塞的工作,也仅仅是阻塞了新创建出来的这个线程,不会导致用来进行异步操作的工作线程阻塞,这样工作线程可以正常调度其他的各种tokio::spawn而不至于陷在那里。
请看下例:

use tokio;

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
    let handle_1 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(10));
        println!("sleeping 10s");
    });
    let handle_2 = tokio::task::spawn(async {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("second spawn!");
    });
    let handle_3 = tokio::task::spawn_blocking(async {
        std::thread::sleep(std::time::Duration::from_secs(5));
        println!("third spawn!");
    });
    tokio::join!(handle_1, handle_2, handle_3);
    println!("hello world!");
}
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值