Understanding multithreading
Now that we understand the different approaches for concurrency in Rust, we can start with the most basic one: creating threads. If you have previously used languages such as Java or C++, you will probably be familiar with the new Thread()
syntax in the former or the std::thread
in the latter. In both cases, you will need to specify some code that the new thread will run, and some extra information the thread will have. In both cases, you can start threads and wait for them to finish.
Creating threads
In Rust, things are similar to the C++ approach, where we have the std::thread
module with the spawn()
function. This function will receive a closure or a pointer to a function and execute it. It will return a handle to the thread, and we will be able to manage it from outside. Let's see how this works:
use std::thread; fn main() { println!("Before the thread!"); let handle = thread::spawn(|| { println!("Inside the thread!"); }); println!...