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:
closure may outlive the current function, but it borrows `a`, which is owned by the current function...