Threads
Rust threads work similarly to threads in other languages:
1. use std::thread;
2. use std::time::Duration;
4. fn main() {
5. thread::spawn(|| {
6. for i in 1..10 {
7. println!("Count in thread: {i}!");
8. thread::sleep(Duration::from_millis(5));
9. }
10. });
12. for i in 1..5 {
13. println!("Main thread: {i}");
14. thread::sleep(Duration::from_millis(5));
15. }
16. }
- Threads are all daemon threads, the main thread does not wait for them.
- Thread panics are independent of each other.
- Panics can carry a payload, which can be unpacked with
downcast_ref.
Key points:
- Notice that the thread is stopped before it reaches 10 — the main thread is not waiting.
- Use
let handle = thread::spawn(...)and laterhandle.join()to wait for the thread to finish. - Trigger a panic in the thread, notice how this doesn’t affect
main. - Use the
Resultreturn value fromhandle.join()to get access to the panic payload. This is a good time to talk about Any.
