本文介绍了交错的作用域如何创建“数据竞赛”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

讨论将多个读取器和对对象的多个可变引用作为可能导致问题的数据争用情况。

The Rust book talks about having multiple readers and multiple mutable references to an object as a data race situation that may lead to issues.

例如,以下代码:

fn main() {
    let mut x = 1;
    let r1 = &mut x;
    *r1 = 2;
    let r2 = &mut x;
    *r2 = 3;
    println!("{}", r1);
    println!("{}", r2);
}

将被Rust编译器拒绝,因为 r1 r2 范围是交织的。

will be rejected by Rust compiler because r1 and r2 scopes are intertwined.

但是这里出了什么问题?我的意思是,这只是一个线程,没有同时读写,因此所有这些语句应严格按顺序执行,并给出确定的可再现结果。

But what is problem here? I mean, this is just one thread and there is no "reading and writing at the same time", so all these statements should be executed strictly sequentially and give deterministic reproducible result.

推荐答案

来自:

但是无论结果如何,迭代器无效都与一场数据竞赛。通常会出现此问题,因为您有一段代码在哈希表上迭代,然后调用在其他模块中定义的子例程。然后,另一个模块将写入同一哈希表。这两个模块本身看起来都不错,只是这两个模块的组合才引起问题。而且由于结果的不确定性,经常会发生代码长时间无法正常工作的情况。直到出现这种情况。

But whatever the outcome, iterator invalidation feels very similar to a data race. The problem often arises because you have one piece of code iterating over a hashtable and then calling a subroutine defined over in some other module. This other module then writes to the same hashtable. Both modules look fine on their own, it’s only the combination of the two that causes the issue. And because of the undefined nature of the result, it often happens that the code works fine for a long time—until it doesn’t.

Rust的类型系统可以防止迭代器失效

Rust’s type system prevents iterator invalidation.

Rust的类型系统不允许像下面的程序那样编译单线程程序,因为它们会导致未定义行为,而 >从技术上讲不是数据争用这个特殊的错误是由于两个独立的代码段以交织的方式使同一数据发生变异而导致的错误,因此它与数据争用非常相似,我相信那就是Rust书试图传达的东西:

Rust's type system disallows single-threaded programs like the one below to compile because they would result in Undefined Behavior and while that technically isn't a data race this particular error is in the same ballpark of "errors caused by two independent pieces of code mutating the same data in an interweaved fashion" so it's very similar to a data race and I believe that's what the Rust book was trying to communicate:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(1, 1);
    map.insert(2, 2);
    map.insert(3, 3);

    for _ in map.iter() {
        map.insert(4, 4); // compile error!
    }
}

这篇关于交错的作用域如何创建“数据竞赛”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:21