gpt4 book ai didi

Rust Arc 如何获取_mut 并在此之后恢复其他 Arc 副本的读取能力?

转载 作者:行者123 更新时间:2023-12-03 11:43:43 37 4
gpt4 key购买 nike

我想知道如何更改 Arc 中的值,然后使 Arc 的其他副本再次有效。

use std::sync::Arc;
use std::thread;
use std::error::Error;
use std::io;
use std::time::Duration;

#[derive(Debug)]
struct El {
n: i64,
}

fn main() -> io::Result<()> {
let mut a = Arc::new(El{n: 5});
let b = Arc::clone(&a);
let th = thread::spawn(move || {
println!(r#"Hello, World!"#);
thread::sleep(Duration::from_millis(1000));
println!("{:?}", b);
});
let mut c = Arc::get_mut(&mut a).unwrap();
c.n = 10;
drop(c);
drop(a);
th.join().expect("some errors occured");
Ok(())
}

这会在突变已经完成并且指针被丢弃的那一刻导致 panic 。如何解决?

最佳答案

你想写Arc的内容在一个线程中阅读另一个线程。在 Rust 中,一个值要么是共享可读的,要么是独占可写的。共享多个引用的Arc线。

您可以通过使用内部可变性来解决此问题,例如通过Arc<Mutex<El>>Arc<RwLock<El>> . MutexRwLock通过阻塞所有读取直到写入完成并在读取锁存在时阻塞所有写入来动态确保共享/排他约束。

例子:

fn main() -> io::Result<()> {
let a = Arc::new(Mutex::new(El{n: 5}));
let b = Arc::clone(&a);
let th = thread::spawn(move || {
println!(r#"Hello, World!"#);
thread::sleep(Duration::from_millis(1000));
println!("{:?}", b.lock().unwrap());
});
a.lock().unwrap().n = 10;
drop(a);
th.join().expect("some errors occured");
Ok(())
}

关于Rust Arc 如何获取_mut 并在此之后恢复其他 Arc 副本的读取能力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073701/

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