首页 > 解决方案 > 如何对具有动态成员的结构采用 Send 和 Sync(未来无法在线程之间安全发送)

问题描述

考虑下面的代码,它使用crate声明了一个带有async方法的特征。async-trait

use std::{io::Result, sync::Arc};

use async_trait::async_trait;
use tokio;

// A trait that describes a power source.
trait PowerSource {
    fn supply_power(&self) -> Result<()>;
}

// ElectricMotor implements PowerSource.
struct ElectricMotor {}

impl PowerSource for ElectricMotor {
    fn supply_power(&self) -> Result<()> {
        println!("ElectricMotor::supply_power");
        Ok(())
    }
}

// A trait that describes a vehicle
#[async_trait]
trait Vehicle {
    async fn drive(&self) -> Result<()>;
}

// An automobile has some kind of power source and implements Vehicle
struct Automobile {
    power_source: Arc<dyn PowerSource>,
}

#[async_trait]
impl Vehicle for Automobile {
    async fn drive(&self) -> Result<()> {
        self.power_source.supply_power()?;
        println!("Vehicle::Drive");
        Ok(())
    }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let driver = ElectricMotor {};
    let controller = Automobile {
        power_source: Arc::new(driver),
    };

    controller.drive().await?;

    Ok(())
}

这不会编译错误“未来无法在线程之间安全地发送”:

error: future cannot be sent between threads safely
  --> src/main.rs:34:41
   |
34 |       async fn drive(&self) -> Result<()> {
   |  _________________________________________^
35 | |         self.power_source.supply_power()?;
36 | |         println!("Vehicle::Drive");
37 | |         Ok(())
38 | |     }
   | |_____^ future created by async block is not `Send`
   |
   = help: the trait `Sync` is not implemented for `(dyn PowerSource + 'static)`
note: captured value is not `Send`
  --> src/main.rs:34:21
   |
34 |     async fn drive(&self) -> Result<()> {
   |                     ^^^^ has type `&Automobile` which is not `Send`
   = note: required for the cast to the object type `dyn Future<Output = Result<(), std::io::Error>> + Send`

error: future cannot be sent between threads safely
  --> src/main.rs:34:41
   |
34 |       async fn drive(&self) -> Result<()> {
   |  _________________________________________^
35 | |         self.power_source.supply_power()?;
36 | |         println!("Vehicle::Drive");
37 | |         Ok(())
38 | |     }
   | |_____^ future created by async block is not `Send`
   |
   = help: the trait `Send` is not implemented for `(dyn PowerSource + 'static)`
note: captured value is not `Send`
  --> src/main.rs:34:21
   |
34 |     async fn drive(&self) -> Result<()> {
   |                     ^^^^ has type `&Automobile` which is not `Send`
   = note: required for the cast to the object type `dyn Future<Output = Result<(), std::io::Error>> + Send`

如果我正确理解错误,它认为这Automobile不是Send因为该power_source属性不是,因此它不能创造一个适当的未来。我的理解是Arc线程安全并实现了Sendand Sync,但我对 Rust 并发性还是很陌生,仍然不完全清楚这意味着什么。

我将如何解决此错误?

标签: asynchronousrustconcurrency

解决方案


您必须修改Automobile定义:

struct Automobile {
    power_source: Arc<dyn PowerSource>,
}

在 rust 中,类型是Send当且仅当其所有成员都是Send(除非您手动且不安全地实现Send)。这同样适用于Sync。所以假设你power_source的不是Send,那么生成的impl Future也不会是Send

修复它的方法是添加以下Send + Sync要求power_source

struct Automobile {
    power_source: Arc<dyn PowerSource + Send + Sync>,
}

但你为什么Sync会问?Send毕竟编译器只是在抱怨。它需要的原因Sync是因为仅当两者兼有时才Arc<T>实现SendTSend Sync

补充阅读:


推荐阅读