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;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
文章
255
粉丝
122
喜欢
308
收藏
128
排名:328
访问:2.9 万
私信
所有博文
社区赞助商