天天看点

013 Rust 异步编程,Send trait 相关示例

async fn Future是否为Send的取决于是否在.await点上保留非Send类型。编译器尽其所能地估计值在.await点上的保存时间。

示例

  • 源码
use std::rc::Rc;

#[derive(Default)]
struct NotSend(Rc<()>);

async fn bar() {}

async fn foo() {
	NotSend::default();
	bar().await;
}

fn required_send(_: impl Send) {}

fn main() {
	required_send(foo());
}
           
  • 说明

上述代码并不会报错。但是,如果我们将代码foo函数修改为如下:

async fn foo() {
	let x = NotSend::default();
	bar().await;
}
           
  • 原因分析

如果我们存储了x变量,那么在await之前,x可能并不会drop,那么也就意味着可能会在线程之间传递。而Rc是不能在线程之间传递的。

  • 解决方式
async fn foo() {
    {
	    let x = NotSend::default();
	}
	bar().await;
}
           

继续阅读