Chapter 3. Comparison of Concurrency in Ruby and Rust

 

Rust promises that data races are compile-time errors. If you’re used to programming in a language without such guarantees, such as Ruby, you’ve probably experienced pain in trying to implement multi-threaded code without data races or in trying to debug a subtle data race. Or perhaps you avoided writing concurrent code at all because of the difficulty! In Rust, the compiler helps you to get concurrency right, and there are no debugging data races at runtime because Rust won’t even let them compile.

Let’s explore what a data race is, what a data race looks like in Ruby, what it looks like if we try to port that Ruby to Rust, and what error messages we get that prevent us from making the same mistake.

By “data race” we mean a condition in code where some code is reading a value from a particular location and other code is writing to the same location at about the same time. Sometimes when running the program, the read happens before the write, which causes one result. Other times the write happens before the read, which causes another result. A data race can also happen when both parts of the code are writing to the same location in potentially different orders. There can also be more than two parts of the code involved, as long as at least one part is writing to the shared location. This nondeterministic behavior can be the source of bugs that are hard to detect, reproduce, and fix.