summaryrefslogtreecommitdiffstats
path: root/src/threads
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/threads/Cargo.toml6
-rw-r--r--src/threads/src/main.rs93
2 files changed, 99 insertions, 0 deletions
diff --git a/src/threads/Cargo.toml b/src/threads/Cargo.toml
new file mode 100644
index 0000000..f210198
--- /dev/null
+++ b/src/threads/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "threads"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
diff --git a/src/threads/src/main.rs b/src/threads/src/main.rs
new file mode 100644
index 0000000..18b2645
--- /dev/null
+++ b/src/threads/src/main.rs
@@ -0,0 +1,93 @@
+use std::thread;
+use std::time::Duration;
+
+use std::sync::mpsc;
+
+fn main() {
+ let handle = thread::spawn(|| {
+ for i in 1..10 {
+ println!("hi number {i} from the spawned thread!");
+ thread::sleep(Duration::from_millis(1));
+ }
+ });
+
+ for i in 1..5 {
+ println!("hi number {i} from the main thread!");
+ thread::sleep(Duration::from_millis(1));
+ }
+
+ handle.join().unwrap();
+
+ let v = vec![1, 2, 3];
+
+ let handle_vec = thread::spawn(move || {
+ println!("Here's a vector: {v:?}");
+ });
+
+ handle_vec.join().unwrap();
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let val = String::from("hi");
+ tx.send(val).unwrap();
+ });
+
+ let received = rx.recv().unwrap();
+ println!("Got: {received}");
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let vals = vec![
+ String::from("hi"),
+ String::from("from"),
+ String::from("the"),
+ String::from("thread"),
+ ];
+
+ for val in vals {
+ tx.send(val).unwrap();
+ thread::sleep(Duration::from_secs(1));
+ }
+ });
+
+ for received in rx {
+ println!("Got: {received}");
+ }
+
+ let (tx, rx) = mpsc::channel();
+
+ let tx1 = tx.clone();
+ 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}");
+ }
+}