Joining threads

To retrieve the spawned thread, Rust uses the join() trait and then unwraps the result.

Figure 5

To make our small example application output, we therefore need to join the spawned thread back to the main thread:

use std::thread;  
fn main()  
{ 
    let threadhandle = thread::spawn(||  
    { 
        "Hello from a thread in your Rust program" 
    }); 
     
    println!("{}", threadhandle.join().unwrap()); 
} 
Code for the alterations can be found in Chapter11/joined_thread.

When we run the code, this time we see the following:

Figure 6

Hold on. That code isn't the same! This is true, and it is due to the spawn accepting a closure (||).

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

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