How it works...

In this recipe, we created two threads using the spawn module of the thread crate. The first thread just prints a statement, but the second thread, apart from printing, also passes and returns a value to the main thread. The main thread is the user-created Rust process that creates the other two threads.

The most important point to learn from this recipe is that the main thread will not wait for the spawned thread to complete, which means that the next println macro won't be executed before the program exits. To ensure that the program waits for the threads to finish, we called the join() module on the join_handle variable of the thread.

We even send a value 17 to a different thread through join_handle, as we sent to the second thread in this case. In the last few lines of the code, we had the match statement, where we check whether the value x has returned from the second thread using join_handle .join().

The preceding three println statements can be observed in any order.

The reason why these statements could be observed in a different order in every execution is that they are scheduled by the OS.

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

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