rust - 为什么我的匹配块中需要发送特征?
问题描述
我认为我的问题与Rust Issue 57017 有关。
以下代码error: future cannot be sent between threads safely
由于future created by async block is not 'Send'
源自async fn execute_fail
. _ 另一方面,async fn execute_work
编译并具有相同的功能和逻辑,execute_fail
但方式不太优雅。
async fn stream() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
async fn process() {}
async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
match stream().await {
Err(err) => {
return Err(err);
}
Ok(()) => {
process().await;
}
}
Ok(())
}
async fn execute_work() -> Result<(), Box<dyn std::error::Error>> {
let mut is_success = false;
match stream().await {
Err(err) => {
return Err(err);
}
Ok(()) => {
is_success = true;
}
}
if is_success {
process().await;
}
Ok(())
}
async fn my_fn() {
tokio::spawn(async {
if let Err(err) = execute_fail().await {
panic!("error here");
}
});
tokio::spawn(async {
if let Err(err) = execute_work().await {
panic!("error here");
}
});
}
给出:
error: future cannot be sent between threads safely
--> src/lib.rs:39:5
|
39 | tokio::spawn(async {
| ^^^^^^^^^^^^ future created by async block is not `Send`
|
::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.11.0/src/task/spawn.rs:127:21
|
127 | T: Future + Send + 'static,
| ---- required by this bound in `tokio::spawn`
|
= help: the trait `Send` is not implemented for `dyn std::error::Error`
note: future is not `Send` as this value is used across an await
--> src/lib.rs:15:13
|
10 | match stream().await {
| -------------- has type `Result<(), Box<dyn std::error::Error>>` which is not `Send`
...
15 | process().await;
| ^^^^^^^^^^^^^^^ await occurs here, with `stream().await` maybe used later
16 | }
17 | }
| - `stream().await` is later dropped here
我想解释一下为什么execute_fail
不按原样编译execute_work
。编译器注释note: future is not
Send as this value is used across an await
对我来说没有意义,因为我看不到在 await 中如何使用任何值。
解决方案
我想解释一下为什么 execute_fail 不能像 execute_work 那样编译。
当你match stream().await
基本上工作时:
let v = stream().await;
match v {
...
}
所以v
在整个匹配过程中都是有效的,这意味着就编译器而言,它的“生命”与process().await
调用重叠。值必须Send
通过调用才能生存await
,因为协程可以在与挂起不同的线程上恢复。
注意:这里的代码可以大大简化:
async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
if let Err(err) = stream().await {
return Err(err);
}
process().await;
Ok(())
}
甚至
async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
stream().await?;
process().await;
Ok(())
}
推荐阅读
- ssh - Ansible sudo 密码丢失
- sql-server - 如何计算 Table Trade 中遗漏的零件以及存在于 Table Part 上的零件?
- svg - 给定svg中的4条曲线,得出圆的半径是否准确?
- android - Vulkan 实例
- python - 将字符串转换为 numpy 数组数组
- javascript - Async once() 调用的 Promise 链接仅在返回实际结果后继续
- javascript - 将复选框值传递给函数
- java - 当我创建一系列数组时,我的 JComboBox 显示空白条目
- c# - 在 Entity Framework Core 中拦截实体的保存
- python - 如何在numpy中返回一个数组列?