gpt4 book ai didi

rust - 如何从 Arc> 获取 T 的所有权?

转载 作者:行者123 更新时间:2023-11-29 07:42:37 25 4
gpt4 key购买 nike

我想从一个受 Mutex 保护的函数返回一个值,但无法理解如何正确地执行它。此代码不起作用:

use std::sync::{Arc, Mutex};

fn func() -> Result<(), String> {
let result_my = Arc::new(Mutex::new(Ok(())));
let result_his = result_my.clone();

let t = std::thread::spawn(move || {
let mut result = result_his.lock().unwrap();
*result = Err("something failed".to_string());
});

t.join().expect("Unable to join thread");

let guard = result_my.lock().unwrap();
*guard
}

fn main() {
println!("func() -> {:?}", func());
}

Playground

编译器提示:

error[E0507]: cannot move out of borrowed content
--> src/main.rs:16:5
|
16 | *guard
| ^^^^^^ cannot move out of borrowed content

最佳答案

在 Rust 1.15 中,您可以使用 Arc::try_unwrapMutex::into_inner :

use std::sync::{Arc, Mutex};

fn func() -> Result<(), String> {
let result_my = Arc::new(Mutex::new(Ok(())));
let result_thread = result_my.clone();

let t = std::thread::spawn(move || {
let mut result = result_thread.lock().unwrap();
*result = Err("something failed".to_string());
});

t.join().expect("Unable to join threads");

let lock = Arc::try_unwrap(result_my).expect("Lock still has multiple owners");
lock.into_inner().expect("Mutex cannot be locked")
}

fn main() {
println!("func() -> {:?}", func());
}

RwLock::into_inner自 Rust 1.6 以来也存在。

关于rust - 如何从 Arc<Mutex<T>> 获取 T 的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29177449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com