Threads

Rust provides a mechanism for spawning native OS threads via the spawn
function, the argument of this function is a moving closure.

  1. use std::thread;
  2. static NTHREADS: i32 = 10;
  3. // This is the `main` thread
  4. fn main() {
  5. // Make a vector to hold the children which are spawned.
  6. let mut children = vec![];
  7. for i in 0..NTHREADS {
  8. // Spin up another thread
  9. children.push(thread::spawn(move || {
  10. println!("this is thread number {}", i);
  11. }));
  12. }
  13. for child in children {
  14. // Wait for the thread to finish. Returns a result.
  15. let _ = child.join();
  16. }
  17. }

These threads will be scheduled by the OS.