沙沙线练习,为什么不取消引用Mutex(Struct)? [英] Rustlings thread exercise, why do I NOT dereference Mutex(Struct)?

查看:234
本文介绍了沙沙线练习,为什么不取消引用Mutex(Struct)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rust,并且没有线程经验。我正在上Rustlings课程,并且已经解决了 threads1.rs 练习,但是我不明白为什么我的 Mutex

I'm learning Rust and have no experience with threads. I'm going through the Rustlings course and I've solved the threads1.rs exercise, but I don't understand why my Mutex struct doesn't need to be dereferenced.

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;
        }
    }
}

基于本书的16.3章,我本来需要分配

*status_shared.jobs_completed

以便获取 jobs_completed 字段,但这会产生错误:

in order to get to the jobs_completed field, but that generates the error:

error[E0614]: type `u32` cannot be dereferenced
  --> src/main.rs:16:13
   |
16 |             *status_shared.jobs_completed += 1;
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

这本书的区别在于它提供了指向简单类型的指针,而上述代码给出了对结构的引用?

Is the difference that the book gives a pointer to a simple type and the above code gives a reference to a struct?

推荐答案

status_shared 的类型为 MutexGuard MutexGuard 实现 DerefMut Deref >特质,其deref目标为 T (在Mutex中存储的类型-在您的情况下为 JobStatus

status_shared is of type MutexGuard. MutexGuard implements the DerefMut and Deref traits, with a deref target of T (the type which is stored inside the Mutex - JobStatus in your case.

在对象后的后使用。锈编译器会自动尝试将其反引用为可以执行请求的操作,因此此处无需显式取消引用。Rust书中的取消引用章节

When you use behind a . behind an object the rust compiler will automatically try to deref it into something where the requested operation can be performed. Therefore the explicit dereferencing is not necessary here. This behavior is described in the Rust book in the Deref chapter

这篇关于沙沙线练习,为什么不取消引用Mutex(Struct)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆