gpt4 book ai didi

rust - 沙沙线练习,为什么不取消对Mutex(Struct)的引用?

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

我正在学习Rust,并且没有线程经验。我正在上RuSTLings类(class),并且已经解决了threads1.rs练习,但是我不明白为什么我的Mutex结构不需要取消引用。

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

struct JobStatus {
jobs_completed: u32,
}

fn main() {
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = Arc::clone(&status);
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
let mut status_shared = status_shared.lock().unwrap();
status_shared.jobs_completed += 1; // why not *status_shared?
}
});

let mut jobs_completed: u32;
loop {
jobs_completed = status.lock().unwrap().jobs_completed;
if jobs_completed < 10 {
println!("waiting... ({} jobs done)", jobs_completed);
thread::sleep(Duration::from_millis(500));
} else {
break;
}
}
}

根据《书》的 Chapter 16.3,我本来需要分配给

*status_shared.jobs_completed

为了到达 jobs_completed字段,但这会产生错误:
error[E0614]: type `u32` cannot be dereferenced
--> src/main.rs:16:13
|
16 | *status_shared.jobs_completed += 1;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

本书为简单类型提供了指针,而上面的代码提供了对结构的引用,这是否有所不同?

最佳答案

status_shared的类型为MutexGuardMutexGuard实现DerefMutDeref特性,其refref目标为T(存储在Mutex中的类型-在您的情况下为JobStatus)。

当您在对象后面的.后面使用时,rust编译器将自动尝试将其重新引用为可以执行请求的操作的对象。因此,此处无需显式取消引用。 Rust本书Deref chapter中对此行为进行了描述

关于rust - 沙沙线练习,为什么不取消对Mutex(Struct)的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60766249/

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