Threads |
can use threads to run codes simultaneously The thread::spawn() function is used to create a new thread the spawn function takes a closure as parameter the closure defines code that should be executed by the thread example prints some text from a main thread and other text from a new thread //import the necessary modules use std::thread; use std::time::Duration; fn main() { //create a new thread thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); //code executed by the main thread for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } }output hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the main thread! hi number 2 from the spawned thread! hi number 3 from the main thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 4 from the main thread!the new thread will be stopped when the main thread ends the thread::sleep() function forces a thread to stop its execution for a short duration allows a different thread to run the threads will probably take turns, but that is not guaranteed depends on how the operating system schedules the threads |
Join Handles |
a spawned thread may not get a chance to run or run completely the main thread completes quickly the function spawn<F, T>(f: F) -> JoinHandle<T> returns a JoinHandle the join() method on JoinHandle waits for the associated thread to finish use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); }output hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 2 from the main thread! hi number 3 from the spawned thread! hi number 3 from the main thread! hi number 4 from the main thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! |