问题描述
我的理解是在 Rust 中不可能在任务之间共享可变状态,那么为什么 Rust 有像 互斥量 语言?他们的目的是什么?
My understanding is that it's not possible to share mutable state between tasks in Rust, so why does Rust has things like mutexes in the language? What's their purpose?
推荐答案
不允许在任务之间共享可变数据"过于简单化.无意冒犯,它也用于 Rust 的许多介绍性材料中,并且有充分的理由.但事实是,Rust 只是想摆脱数据竞争;不共享任何内容是首选方法,但不是唯一方法.Rust 还希望成为一种与 C 和 C++ 相同的系统编程语言,因此它不会随意完全删除某些功能或性能优化.但是,通常共享可变内存并不安全(数据竞争等),因此如果您需要它,则必须通过将其包装在 unsafe
块中来确认责任.
"Sharing mutable data between tasks is not allowed" is an oversimplification. No offense meant, it's also used in much introductory material on Rust, and for good reasons. But the truth is, Rust just wants to get rid of data races; not sharing anything is the preferred approach but not the only. Rust also wants to be a system programming language in the same sense as C and C++ are, so it won't nilly-willy completely remove some capability or performance optimization. However, in general shared mutable memory is not safe (data races etc.) so if you want it, you will have to acknowledge the responsibility by wrapping it in unsafe
blocks.
幸运的是,一些使用共享可变内存的模式是安全的(例如,使用适当的锁定规则).当这些模式被识别并被认为足够重要时,有人会编写一些不安全
代码,他们说服自己(或者甚至证明")暴露了一个安全的接口.换句话说:使用接口的代码永远不能违反 Rust 的各种安全要求.例如,虽然 Mutex
允许您在不同时间从不同任务访问可变内存,但它从不允许任务之间别名(即同时访问),因此数据竞争被阻止.
Luckily, some patterns of using shared mutable memory are safe (e.g. using proper locking discipline). When these patterns are recognized and considered important enough, someone writes some unsafe
code that they convince themselves (or perhaps even "prove") exposes a safe interface. In other words: Code using the interface can never violate the various safety requirements of Rust. For example, while Mutex
allows you to access mutable memory from different tasks at different times, it never permits aliasing among tasks (i.e. access at the same time), so data races are prevented.
这篇关于如果不允许在任务之间共享可变状态,为什么 Rust 有互斥体和其他同步原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!