November 2017
Intermediate to advanced
264 pages
5h 45m
English
A thread can be created by spawning it; this creates an independent detached child thread that in general can outlive its parent. This is demonstrated in the following code snippet:
// code from Chapter 9/code/thread_spawn.rs:
use std::thread;
use std::time;
fn main() {
thread::spawn(move || {
println!("Hello from the goblin in the spawned thread!");
});
}
The argument to spawn is a closure (here, without parameters, it is indicated as ||), which is scheduled to execute independently from the parent thread, which is shown here as main(). Notice that it is a moving closure which takes ownership of the variables in a given context. Our closure here is a simple print statement, but in a real situation this could be replaced ...
Read now
Unlock full access