-
-
Save piboistudios/ad911b0349c90a68d5ad69a0567a1e55 to your computer and use it in GitHub Desktop.
[RUST]Concurrency 1.1 (#4)
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; | |
fn main() { | |
concurrency_demo_1(); | |
concurrency_demo_2(); | |
} | |
// this simply demonstrates how to move data from an outer scope into a thread's scope: | |
fn concurrency_demo_1() { | |
let v = vec![1, 2, 3]; | |
// by default thread::spawn -borrows- any variables from the outer scope | |
// the 'move' keyword makes sure that we take ownership | |
// therefore for hte lifetime of the thread v is guaranteed to exist | |
let handle = thread::spawn(move || { | |
println!("Here's a vector: {:?}", v); | |
}); | |
// without the line below, there will be no output | |
handle.join().unwrap(); | |
} | |
// use the Multiple Producer, Single Consumer namespace for Channels | |
use std::sync::mpsc; | |
fn concurrency_demo_2() { | |
// we use a destructuring statement to gather a tuple from the mpsc::channel() call | |
// channel returns the transmitter or upstream and receiver or downstream | |
// put values in the upstream, retrieve them in the downstream | |
let (transmiter, receiver) = mpsc::channel(); | |
println!("Sending values."); | |
thread::spawn(move || { // note you can send multiple values | |
let val1 = "hi".to_string(); | |
let val2 = "bye".to_string(); | |
thread::sleep(Duration::from_millis(1000)); | |
transmiter.send(val1).unwrap(); | |
transmiter.send(val2).unwrap(); | |
}); | |
// the following two lines will block until a value is available | |
// try_recv is the non-block counterpart that retuns a Result<T> (not Option<T>), hence we must unwrap() | |
// to implicitly handle the errors | |
let received = receiver.recv().unwrap(); | |
let received2 = receiver.recv().unwrap(); | |
println!("Got: {} and {}", received, received2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment