What is thread-safety?

thread-safety is the property of a type or a piece of code that, when executed or accessed by multiple threads, does not lead to unexpected behavior. It refers to the idea that data is consistent for reads while being safe from corruption when multiple threads write to it.

Rust only protects you from data races. It doesn't aim to protect against deadlocks as they are difficult to detect. It instead offloads this to third-party crates such as the parking_lot crate.

Rust has a novel approach to protecting against data races. Most of the thread-safety bits are already embedded in the spawn method's type signature. Let's look at its type signature:

fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static

That's a scary-looking type signature. Let's make it less scary by explaining what each of the parts mean.

spawn is a generic function over F and T and takes a parameter, f, and returns a generic type called JoinHandle<T>. Following that, the where clause specifies multiple trait bounds:

  • F: FnOnce() -> T: This says that F implements a closure that can be called only once. In other words, f is a closure that takes everything by value and moves items referenced from the environment.
  • F: Send + 'static: This means that the closure must be Send and must have the 'static lifetime, implying that any type referenced from within the closure in its environment must also be Send and must live for the entire duration of the program.
  • T: Send + 'static: The return type, T, from the closure must also implement the Send + 'static trait.

As we know, Send is a marker trait. It is just used as a type-level marker that implies that the value is safe to be sent across threads; most types are Send. Types that don't implement Send are pointers, references, and so on. In addition, Send is an auto trait or an automatically derived trait whenever applicable. Compound data types such as a struct implement Send if all of the fields in a struct are Send.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset