文章目录
Rust的并发编程(三)
并发,是指在宏观意义上同一时间处理多个任务。并发的方式一般包含为三种:多进程、多线程以及最近几年刚刚火起来的协程。
协程
协程与进程和线程不是一个级别的概念。进程和线程都是操作系统任务调度的单位,而协程不是,他并不受操作系统的约束,只是通过异步的手段,让单线程的程序有了并发的能力。
协程的并发需要自己的程序实现调度,而Rust的标准库中并没有提供调度协程的模块,需要通过第三方库futures来进行,futures库的资料能查到的很少,大部分都是在讲怎么创建协程,而执行协程都是阻塞的,我没有找到非阻塞的方法启动协程,这样就实现不了并发的效果。
创建协程需要先引入futures库,在Cargo.toml文件的dependencies中添加依赖:
[dependencies]
futures = ""
然后在代码中添加:
use futures;
在协程函数的定义前添加async关键字:
async fn coroutine() {
let mut n = 0;
while n < 100 {
n += 1;
println!("coroutine:{}", n);
sleep(Duration::from_secs_f64(0.3));
}
}
添加了async关键字后,函数返回Future对象:
let coroutine = coroutine();
然后使用futures::executor::block_on函数执行协程:
futures::executor::block_on(coroutine);
完整的代码如下:
use futures;
use std::thread::sleep;
use std::time::Duration;
async fn coroutine() {
let mut n = 0;
while n < 100 {
n += 1;
println!("coroutine:{}", n);
sleep(Duration::from_secs_f64(0.3));
}
}
fn main() {
let coroutine = coroutine();
futures::executor::block_on(coroutine);
}
执行的效果是每隔0.3秒就打印一行,为了验证并发效果,在主函数中添加一段时间的等待,看等待的过程中协程是否在执行:
use futures;
use std::thread::sleep;
use std::time::Duration;
async fn coroutine() {
let mut n = 0;
while n < 100 {
n += 1;
println!("coroutine:{}", n);
sleep(Duration::from_secs_f64(0.3));
}
}
fn main() {
let coroutine = coroutine();
println!("coroutine created");
sleep(Duration::from_secs(5));
println!("block_on coroutine");
futures::executor::block_on(coroutine);
}
这个例子验证了Future的懒惰性,它并不是在创建后就执行,而是一直等到block_on被调用时才会执行,而block_on是阻塞的,即协程在执行过程中,主函数无法进行其他的工作。
与async关键字相对的,还有一个.await,与block_on类似,阻塞的等待协程的执行,不同的是,await只能用在协程函数内:
use futures;
use std::thread::sleep;
use std::time::Duration;
async fn coroutine1() {
let c = coroutine2();
c.await;
let mut n = 0;
while n < 100 {
n += 1;
println!("coroutine1:{}", n);
sleep(Duration::from_secs_f64(0.3));
}
}
async fn coroutine2() {
let mut n = 0;
while n < 100 {
n += 1;
println!("coroutine2:{}", n);
sleep(Duration::from_secs_f64(0.3));
}
}
fn main() {
let coroutine = coroutine1();
println!("coroutine created");
sleep(Duration::from_secs(5));
println!("block_on coroutine");
futures::executor::block_on(coroutine);
}
主函数中执行了协程coroutine1,coroutine1又执行了coroutine2,这段代码执行时,会先输出coroutine2的100条信息,然后才输出coroutine1的内容,同样无法实现两个协程的并发。
最终,我也没有找到实现协程并发的方法,但是这肯定是可以的。futures只是协程的基础,还有一个库名为Tokio,是一个事件驱动的非阻塞I / O平台,用于使用Rust编程语言编写异步应用程序。对于Tokio留在以后学习。
附Tokio中文文档地址:https://tokio-zh.github.io/document/