src/concurrency/threads/plain.md
Rust threads work similarly to threads in other languages:
# // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 0..10 {
println!("Count in thread: {i}!");
thread::sleep(Duration::from_millis(5));
}
});
for i in 0..5 {
println!("Main thread: {i}");
thread::sleep(Duration::from_millis(5));
}
}
main.Any::downcast_ref.Run the example.
main ends the program and spawned threads do not make it
persist.
pthreads/C++ std::thread/boost::thread if desired.How do we wait around for the spawned thread to complete?
thread::spawn returns a JoinHandle. Look at the docs.
JoinHandle has a .join() method that blocks.Use let handle = thread::spawn(...) and later handle.join() to wait for
the thread to finish and have the program count all the way to 10.
Now what if we want to return a value?
Look at docs again:
thread::spawn's closure returns TJoinHandle .join() returns thread::Result<T>Use the Result return value from handle.join() to get access to the
returned value.
Ok, what about the other case?
main.Any.Now we can return values from threads! What about taking inputs?
If we want to borrow?