Simple thread (with fake work)
This is a simple example of using threads in Rust, with a huge problem that we can easily miss in this example. Take a look at the code.
use std::thread; fn main() { println!("Before starting: {:?}", thread::current().id()); thread::spawn(|| { println!("In thread {:?}", thread::current().id()); for i in 1..10000000 { let _n = i + i; } }); for i in 1..10000000 { let _n = i + i; } println!("After ending: {:?}", thread::current().id()); }
- We can easily start a new thread using the spawn function of the thread crate.
- We even have two loops one in the main thread and one in the created thread to "do some work". It seems to work.
- There is a slight problem though. Our main program might end before the thread can do the actual work and this example we don't even see that.
Before starting: ThreadId(1)
In thread ThreadId(2)
After ending: ThreadId(1)