简体   繁体   English

对于 Rust 中的多个可变引用,同步如何成为问题?

[英]How is synchronizing is a problem for multiple mutable references in Rust?

I was reading Rust documentation section 4 and saw a code like this:我正在阅读 Rust 文档第 4 节并看到这样的代码:

let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s;

println!("{}, {}", r1, r2);

So the documentation says that you cannot have multiple mutable references in Rust.所以文档说你不能在 Rust 中有多个可变引用。 Okay, makes sense but doc says three behaviors occurs if you could use, one of them is:好的,有道理,但 doc 说,如果您可以使用,会发生三种行为,其中一种是:

There's no mechanism being used to synchronize access to the data.没有用于同步数据访问的机制。

Is there a need of mechanism to synchronize it?是否需要机制来同步它? I mean we already use pointers to the heap or to another pointer that points to the heap.我的意思是我们已经使用了指向堆或指向堆的另一个指针的指针。

锈蚀图

I mean in this diagram, let's say that we have s2 and s3 as mutable references to s1 .我的意思是在这张图中,假设我们有s2s3作为对s1可变引用。 s1 already has a pointer to the heap so s2 and s3 has pointers to s1. s1已经有一个指向堆的指针,所以s2s3有指向 s1 的指针。 When we change s2 or s3 doesn't the memory change in the heap?当我们改变s2s3时,堆中的内存不会改变吗?

let mut s1 = String::from("Hello");
let s2 = &mut s1;
s2.push_str(", world");

In here the memory in the heap that s1 points to is changed so the s3 already points to that memory so doesn't it already synchronized?在这里, s1指向的堆中的内存发生了变化,因此s3已经指向该内存,所以它不是已经同步了吗?

I just assume that we could have multiple mutable references, i know there are another problems for this case but one of the three problems according to Rust docs was this.我只是假设我们可以有多个可变引用,我知道这种情况还有另一个问题,但根据 Rust 文档的三个问题之一就是这个。

Imagine if the following was allowed:想象一下,如果允许以下内容:

let mut maybe_five = Some(5);
let mut zero = 0;

// first mutable borrow
let ref_five = &mut maybe_five;

// second mutable borrow
// number_ref is a reference inside maybe_five's Some
let number_ref = match &mut maybe_five {
    Some(ref mut five) => five,
    _ => &mut zero,
};

// invalidate number_ref by making the value it points to invalid
*ref_five = None;

// now we write into a None???
*number_ref = 10;

We would be able to do all kinds of undefined behavior in safe rust.我们将能够在安全的 Rust 中做各种未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM