AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79118831
Accepted
Fee
Fee
Asked: 2024-10-24 00:27:06 +0800 CST2024-10-24 00:27:06 +0800 CST 2024-10-24 00:27:06 +0800 CST

每次创建未来时,`pub fn long(&self) -> impl Future<Output = ()> + 'static` 是否会泄露数据?

  • 772

基本上,基于这个答案:

pub fn long() -> impl Future<Output = ()> + 'static {
  let s = String::from("what is the answer?");
  async move {
     // `s` gets moved into this block
     println!("{s}");
  }
}

#[tokio::main]
async fn main() {
    let future = long(); // Create the future
    future.await; // Await the future, it will complete, and `s` will be dropped
}

我的问题是,这个'static界限是否会在每次创建未来时泄漏数据?或者'static这里的界限是否意味着特征实现必须是静态的?(例如,函数定义在内存中)。到目前为止,我有:

  1. 问 ChatGPT:它说awaiting 放弃了未来
  2. 书中这段话没有回答。
  3. 阅读《rustonomicon》中关于终身强制的规定
  4. 阅读 类似的 问题

我主要想概念化“静态”的需要和效果;代码已经可以运行了。

背景

我有一个阅读器可以读取某些部分,而对于另一个阅读器,它可能需要先加载其他数据才能继续。我想到最好的办法是:

type Image = Vec<u8>;
#[async_trait]
trait Reader {
    async fn read_into_buffer(&self, offset: u32, buf: &mut [u8]) {
       sleep(2);
       buf.fill(42);
    }
}

struct Decoder<R: Reader> {
  reader: Arc<R>,
  images: HashMap<u32, Arc<Image>>,
}

impl<R> Decoder<R> {
  fn decode_chunk(&self, overview: u32, chunk: usize) -> Result<(),impl Future<Output = Vec<u8>> {
    if let Some(im) = self.images.get(overview) {
      // cheap clones because they are Arcs
      let image = im.clone()
      let r = self.reader.clone()
      async move {
        // don't mention `self` in here
        let buf = vec![0; 42];
        let offset = image[chunk];
        r.read_into_buffer(offset, buf);
        buf
      }
    } else {
        Err(())
    }
  }

  async fn load_overview(&mut self, offset: u32) {
    let buf = vec![0;42];
    self.reader.read_into_buffer(offset, buf).await;
    self.images.insert(offset, buf);
  }
}

可以这样使用:

decoder.load_overview(42).await;
let chunk_1 = decoder.decode_chunk(42, 13).unwrap(); // no await'ing
let chunk_2_err = decoder.decode_chunk(13).unwrap_err(); // chunk 13 isn't loaded
decoder.load_overview(13).await;
let chunk_2 = decoder.decode_chunk(13, 13).unwrap();
let res = (chunk_1.await, chunk_2.await)
asynchronous
  • 1 1 个回答
  • 64 Views

1 个回答

  • Voted
  1. Best Answer
    Finn Bear
    2024-10-24T00:49:00+08:002024-10-24T00:49:00+08:00

    没有内存泄漏。堆分配的内容(如s)将在完成之前被删除.await。完成后,未来的堆栈分配将超出范围.await。

    你可以将返回想象Future<Output = ()> + 'static成一个状态机,如下所示enum:

    enum ReturnedFuture {
        Created{s: String},
        Done
    }
    

    enum由于'static没有非引用,因此'static实现Future如下(我人为地简化了很多方法签名):

    impl Future for ReturnedFuture {
        fn poll(&mut self) -> Poll<()> {
             match self {
                  Self::Created{s} => {
                      println!("{s}");
                      // Here is where `s` (heap allocation) will be automatically dropped.
                      *self = Self::Done;
                  }
                  Self::Done => {}
             }
             Poll::Ready(())
        }
    }
    

    你可以想象.await像这样实现(屈服于运行时和通过注册唤醒的复杂性Poll::Pending已async被Context省略):

    let future = long();
    // future.await;
    let result = {
        // future is moved to a mutable variable
        let mut fut = future;
        loop {
            let poll = fut.poll();
            if poll.is_ready() {
                break poll;
            } else {
                unreachable!("ReturnedFuture never returns pending, so this complexity has been elided");
            }
        }
        // fut goes out of scope here (stack allocation is dropped).
    };
    // future no longer exists here (it was moved already)
    

    请参阅最后两个代码块中的注释以了解何时释放内存。

    • 2

相关问题

  • 异步函数作为哈希图值类型

  • 观看 Rust 频道

  • 具有 Boxed 异步回调类型字段的结构体的生命周期必须比“static”长

  • 使用 JetPack Compose 中异步任务的结果更新文本字段的最简单方法

  • 在使用粗粒度锁访问的数据结构中使用 RefCell 是否安全?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve