Back to threading

Now we have seen how closures work and their importance, we can continue with threading.

If we consider Figure 5, we can use a closure to return a value from one of the subthreads:

use std::thread;  
fn main()  
{ 
    let x = 10; 
    thread::spawn(|| (println!("x is {}", x); )); 
} 

Will this work as is? Unfortunately not. We are borrowing x, which we can't do because of ownership problems. However, we could add move to the invocation:

use std::thread;  
fn main()  
{ 
    let x = 10; 
    thread::spawn(move || (println!("x is {}", x); )); 
} 

The thread will take ownership of the copy of x rather than borrow the value. By taking ownership, Rust prevents a common issue with any form of threading: race conditions. If you recall, from the start of this chapter I said that conventional threading has no guarantees of when a thread will return, which can cause all sorts of issues. Typically, other languages use mutexes to try and prevent the race condition (mutex stands for mutual exclusion, which should give an idea as to how they work). By taking ownership, Rust does a lot to prevent racing.

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

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