Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Forked from rust-play/playground.rs
Last active July 12, 2018 19:07
Show Gist options
  • Save piboistudios/e0fa306838c0934cbb42825381a6147f to your computer and use it in GitHub Desktop.
Save piboistudios/e0fa306838c0934cbb42825381a6147f to your computer and use it in GitHub Desktop.
[RUST]Concurrency 1.0 (#3)
use std::thread;
use std::time::Duration;
// this simple example spwans a thread and runs an operation while running the same operation on the main thread
fn main() {
// the thread::spawn function expects a Closure; Rust closure syntax is |params_list...| { expr body }
// if the exprsesion is one line curly braces can be omitted
// type annotations are optional in closures, as Rust implicitly infers the types the first time the Closure is called
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
// without this line, the first loop won't finish!
handle.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment