Multithreading in Rust
-
std::thread
provides access to an OS-level abstraction of threads (aka ‘native threads’)- on Linux/Windows, they are independently and preemptively scheduled on multiple cores where available
- may separately block on I/O calls
-
visible via
ps(1)
- POSIX-derived API for thread creation and joining
Thread Creation and Joining
-
Threads are represented as closures that run in a new thread
-
Argument may be passed via closure, subject to borrowing rules.
-
move
keyword may move ownership of items into the thread, provided they implement theSend
marker trait -
By default, borrowing rules prevent accesses to objects not moved into thread because the thread may have a longer lifetime than the creator
-
Return values may received by the thread creator via handles that can be joined.
-
dropping
JoinHandle
detaches threads -
ownership rules of
JoinHandle
prevents double-joining; i.e.,.join
consumes ownership
-
dropping
Thread Creation Example
/* Example 1. Create a thread and join it. */
use std::thread;
fn main() {
let msg = "Hello, World";
let handle = thread::spawn(move || {
println!("{}", msg);
"some result"
});
match handle.join() {
Ok(threadexitvalue) => {
println!("Thread returned {}", threadexitvalue);
},
Err(err) => {
println!("Thread join failed {:?}", err);
}
}
}