4 ms·
How does Rust prevent data races?
by nyc_pizzadev 4y ago
How does Rust prevent data races?
- DougBTX 4y ago> Data races are mostly prevented through Rust's ownership system: it's impossible to alias a mutable reference, so it's impossible to perform a data race. https://doc.rust-lang.org/nomicon/races.html https://doc.rust-lang.org/nomicon/races.html
- Sankozi 4y agoDefinition of data race on that page is very limited. Also on the same page "Data races are mostly prevented through Rust's ownership system".
- kaba0 4y agoRust does prevent data races (as in multiple threads writing to the same memory location is explicitly forbidden by the borrow checker), but it doesn’t prevent race conditions, which is a more general family of concurrency bugs. In short, the borrow checker allows a single owner at all times, or it allows references to the object, abiding these rules: it may have any number of read-only references (they are safe to share), OR a single read-write reference.
- duped 4y agoA data race occurs when two or more parallel processes access the same data and at least one of them is mutating it. Safe Rust forbids this through ownership and move semantics along with lifetime analysis. You may create any number of immutable aliases to data, or exactly one mutable alias. You cannot mix the two. Unsafe allows you to (kind of) sidestep the automatic checking, but its your responsibility to uphold those conditions.
- commandlinefan 4y agoSounds more or less (and pardon me if I'm oversimplifying) Java's "synchronized" keyword that most people stay away from just because it slows the code down so much you don't get the benefit of parallelization.
- duped 4y agoThey couldn't be more different. Java's synchronized keyword changes how code is interpreted to use expensive locking and data fences in order to prevent logical race conditions. Rust's semantics do not alter the compiled code or insert any locking behavior. They prevent you from writing incorrect code to begin with. In other words, Rust doesn't do anything magical to deal with data races at run time. It prevents you from expressing programs that have data races in the first place. It's a compile time analysis, not a run time behavior.
- commandlinefan 4y agoInteresting, thanks for clarifying.
- gnulinux 4y agoRust type system has primitive traits Send and Sync that formalize behavior expected for safe multithreaded concurrency. This way compiler can statically analyze the program and determine if it's safe.