main.rs (1103B)
1 use std::{ 2 thread::{self, sleep}, 3 time::Duration, 4 }; 5 6 /// A short example of how to use OS threads 7 /// 8 /// In this example we simply spawn several OS threads and put them to sleep. 9 /// Sleeping is essentially the same as yielding to the OS scheduler with 10 /// a request to be re-scheduled to run after a certain time has passed. 11 /// 12 /// Using OS threads aren't always the best choice, there are many 13 /// alternatives, such as fibers and green threads, etc. 14 fn main() { 15 println!("So, we start the program here!"); 16 let thread_1 = thread::spawn(move || { 17 sleep(Duration::from_millis(200)); 18 println!("The long running tasks finish last!"); 19 }); 20 21 let thread_2 = thread::spawn(move || { 22 sleep(Duration::from_millis(100)); 23 println!("We can chain callbacks..."); 24 let thread_3 = thread::spawn(move || { 25 sleep(Duration::from_millis(50)); 26 println!("...like this!"); 27 }); 28 thread_3.join().unwrap(); 29 }); 30 println!("The tasks run concurrently!"); 31 32 thread_1.join().unwrap(); 33 thread_2.join().unwrap(); 34 }