rust - mutex.lock是否需要提前结束其生命周期?

标签 rust borrow-checker

我有一段 Rust 代码。

use std::sync::Mutex;

struct Demo {
    a: Mutex<()>
}

fn return_demo() -> Demo {
    let d = Demo {
        a: Mutex::new(())
    };

    let _l = d.a.lock().unwrap();

    return d;
}

fn main() {
    return_demo();
}

上述代码编译错误如下。

error[E0505]: cannot move out of `d` because it is borrowed
  --> src/bin/main15.rs:14:12
   |
8  |     let d = Demo {
   |         - binding `d` declared here
...
12 |     let _l = d.a.lock().unwrap();
   |              ---------- borrow of `d.a` occurs here
13 |
14 |     return d;
   |            ^ move out of `d` occurs here
15 | }
   | - borrow might be used here, when `_l` is dropped and runs the `Drop` code for type `MutexGuard`

我有两个问题:

  1. 编译器针对此代码给出的错误意味着什么?
  2. 为什么编译器不能自动处理这种情况,比如先执行“drop”然后返回?

最佳答案

What does the error given by the compiler for this code mean?

互斥锁被锁借用,因此无法移动。

Why can't the compiler automatically handle this situation, such as executing "drop" first and then returning?

因为这会链接程序的可观察行为,所以编译器不允许这样做。

有人可能会争辩说,提前释放锁不会改变程序的行为,但即使这是真的(而且不一定是真的 - 程序可能依赖于在某个时间释放锁,例如因为不安全)代码正在使用受其保护但不在互斥锁下的数据)编译器无法知道这一点。 Drop 可以执行任何操作,例如打印,因此不允许提前执行它。

关于rust - mutex.lock是否需要提前结束其生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75782950/

相关文章:

rust - `T : ' static`是什么意思?

rust - 是否可以使用 rustdoc 对 API 的各个部分进行分组?

rust - 未装箱的闭包类型各不相同

rust - 缓存自引用函数导致 Rust

rust - 如何在两个地方存储结构?

rust - 如果让借用在返回后保留,即使使用 #![feature(nll​​)]

rust - 为什么通过提取方法进行重构会触发借用检查器错误?

rust - 具有可变借用的函数的返回类型有什么影响?

rust - 如何将 C 可变长度数组代码转换为 Rust?

struct - 如何在结构定义中初始化数组?