Understanding Send and Sync traits

In the previous neural network example, we used a static data structure that was shared between threads without being wrapped in a counter or lock. It contained locks, but why was the outer data structure permitted to be shared?

To answer this question, let's first review the rules of ownership:

  • Each value in Rust has a variable that's called its owner
  • There can only be one owner at a time
  • When the owner goes out of scope, the value will be dropped

With these rules in mind, let's try to share a variable across threads, as follows:

use std::thread;fn main() {   let a = vec![1, 2, 3];   thread::spawn(|| {      println!("a = {:?}", a);   });}

If we try to compile this, then we will get an error complaining of the following: ...

Get Hands-On Functional Programming in Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.