-
-
Save piboistudios/e0fa306838c0934cbb42825381a6147f to your computer and use it in GitHub Desktop.
[RUST]Concurrency 1.0 (#3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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