diff --git a/.idea/misc.xml b/.idea/misc.xml index 55c8377..1c9acf9 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -28,6 +28,7 @@ + diff --git a/.idea/rust.iml b/.idea/rust.iml index 8165c4c..971bd3a 100644 --- a/.idea/rust.iml +++ b/.idea/rust.iml @@ -114,6 +114,10 @@ + + + + @@ -140,6 +144,7 @@ + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index c6ba616..bdb3b8d 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -15,10 +15,10 @@ - + - - + + @@ -95,6 +95,7 @@ @@ -128,12 +129,12 @@ - + - + @@ -167,7 +168,7 @@ - + @@ -195,7 +196,7 @@ - + - + @@ -273,11 +274,11 @@ + - @@ -317,8 +318,8 @@ - - + + @@ -326,7 +327,7 @@ - + @@ -756,8 +757,15 @@ - - + + + + + + + + + diff --git a/threads/Cargo.toml b/threads/Cargo.toml new file mode 100644 index 0000000..70853ce --- /dev/null +++ b/threads/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/threads/src/main.rs b/threads/src/main.rs new file mode 100644 index 0000000..4b38884 --- /dev/null +++ b/threads/src/main.rs @@ -0,0 +1,68 @@ +use std::thread; +use std::time::Duration; +use std::sync::mpsc; + +fn basic_thread_usage() { + let v = vec![1, 2, 3]; + + // Move is a keyword, not a parameter, it gives + // ownership of closure values to the thread + let handle = thread::spawn(move|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + println!("Here's a vector: {:?}", v); + thread::sleep(Duration::from_millis(1)); + } + }); + + handle.join().unwrap(); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } +} + +fn messages_example() { + let (tx, rx) = mpsc::channel(); + + let tx1 = mpsc::Sender::clone(&tx); + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx1.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + + for received in rx { + println!("Got: {}", received); + } +} + +fn main() { + basic_thread_usage(); + + messages_example(); +}