mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-01 17:34:25 +02:00
The new Chromium class likes — like me! — to use dashes in the writing! However, I believe it should use an em-dash instead of the hyphen. Luckily this is easy: we have enabled “typographic quotes” in `mdbook`, which also handles the conversion of `---` to `—` in the generated HTML. So I normalized the single existing em-dash to a triple-dash to make it more consistent (and hopefully make it easier for translators to consistently enter these characters).
1.1 KiB
1.1 KiB
Threads
Rust threads work similarly to threads in other languages:
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("Count in thread: {i}!");
thread::sleep(Duration::from_millis(5));
}
});
for i in 1..5 {
println!("Main thread: {i}");
thread::sleep(Duration::from_millis(5));
}
}
- 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
.
- Panics can carry a payload, which can be unpacked with
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
Result
return value fromhandle.join()
to get access to the panic payload. This is a good time to talk aboutAny
.