How it works...

In this recipe, we use Rust's standard library, namely std::thread, for creating a thread that would allow your Rust code to run in parallel.

We created a variable named x using the let keyword and assigned it the value 1, which we passed to the thread created by the thread::spawn() method. This method accepts a closure and it will be executed as a different thread; the result that it returns is collected in the handle variable of the main or parent thread, which is the originator of the child thread. The parent or main thread waits until the child thread completes the task, and by assigning it to a variable, we collect the information from the child thread in the handle variable.

As closures have the ability to capture variables from their environment, we brought the data from the child thread to the parent thread, but we have to do this carefully using the move closure. If you don't use move, you will get a compile-time error as, by default closures capture variables by reference, and we only have the reference to x. This is a problem of dangling pointers. The move closure prevents this by moving the variable from other environments to themselves.

At last, we called the join() and unwrap() methods to print the result from the child thread.

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

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