m0_57781768 2022-10-24 22:34 采纳率: 100%
浏览 5
已结题

如何像在 Go 中使用 goroutine 一样在 Rust 中启动后台函数?

我在学习 Rust ,我原来是学习Go的。
使用 Go 很容易在 goroutine 中启动一个函数,即使我返回父函数,例如:

用代码块功能插入代码,请勿粘贴截图
func doSomething() {
  // do something

  go func() {
    // do something longer
    // this doesn't block doSomething and also handles optional errors
  }()

  return // something
}

我怎样才能在 Rust 中做到这一点?

假设我有这个代码:

#[tokio::main]
async fn main() {
    doSomething().await;
}

async fn doSomething() {
    // do something

    // How to start something longer here?
    // I don't want to block doSomething function here, this is only a background task I need to start.

    return // something
}
  • 写回答

1条回答 默认 最新

  • 快撑死的鱼 2022-10-24 22:47
    关注

    首先。您必须使用await语法。所以你的主要功能应该是这样的 Futurefuture.await

    #[tokio::main]
    async fn main() {
      doSomething().await;
    }
    ```rust
    至于您的主要问题async是生锈设计中的非阻塞。如果一个未来还没有准备好取得进展,它会返回给调度程序,同时另一个未来可能会运行。我猜你想生成另一个将同时运行到未来的任务。要做到这一点(因为您使用的是 tokio,所以其他执行器有自己的功能)。所以你的例子可以这样重写:
    ```rust
    async fn foo() {
        // does some work
    }
    
    async fn doSomething() {
        // do something
    
        tokio::spawn(async {
            foo().await;
        });
    
        return // something
    }
    ```rust
    如果您刚开始学习异步 rust,那么我建议您阅读 Tokio 的异步教程
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月1日
  • 已采纳回答 10月24日
  • 创建了问题 10月24日

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM